gpt4 book ai didi

vba - 如何检测单元格格式的变化?

转载 作者:行者123 更新时间:2023-12-02 02:15:41 33 4
gpt4 key购买 nike

我想在 Excel 工作表中嵌入一个过程,该过程将检测单元格格式何时发生变化,例如从文本到数字。

但我不知道如何获取单元格的格式类型。我尝试使用 Worksheet_Change事件处理程序检查数据类型,如下:

Private Sub worksheet_change(ByVal Target As Range)

If Target.Address = "a1" Then
If VarType(Target) <> 5 Then
MsgBox "cell format has been changed"
End If
End If


End Sub

但使用此代码后,如果我将单元格 A1 的数据类型从数字更改为文本,Worksheet_Change没有被触发;仅当我更改单元格的内容时才会调用事件处理程序。

此外,此过程还可以检测内容是否从数字更改为字母字符串,例如从“35.12”到“abcd”,但不是数字型数字到文本型数字;如果我将单元格 B1 设置为文本,然后输入“40”,然后将单元格 B1 的内容粘贴到单元格 A1 中,vartype()仍然返回“5”,因此不会触发警报。

无论内容类型是否已更改,如何检测格式已更改?

最佳答案

好问题!

如果您只想在 NumberFormat 更改上触发事件(您似乎错误地将其称为数据格式,NumberFormat 是您想要的属性),以下是一个很好的示例。

我正在拦截所有选择更改事件并检查是否有任何 NumberFormat 发生更改。

Option Explicit

'keep track of the previous
Public m_numberFormatDictionary As New dictionary
Public m_previousRange As Range

Private Sub Worksheet_SelectionChange(ByVal Target As Range)

'requires reference to Microsoft Scripting Runtime

Dim c As Variant
Dim wasChange As Boolean


Debug.Print "***********************"

'make sure you had a previous selection and it was initialized
If m_numberFormatDictionary.Count > 0 And Not m_previousRange Is Nothing Then

'Iterate through all your previous formattings and see if they are the same
For Each c In m_previousRange
Debug.Print "Found " & c.NumberFormat & " in " & c.Address
Debug.Print "Stored value is " & m_numberFormatDictionary(c.Address) & " in " & c.Address

'print out when they are different
If c.NumberFormat <> m_numberFormatDictionary(c.Address) Then
Debug.Print "~~~~~~ Different ~~~~~~"
wasChange = True
End If

Next c
End If

'clear previous values
m_numberFormatDictionary.RemoveAll

'Make sure you don't error out Excel by checking a million things
If Target.Cells.Count < 1000 Then

'Add each cell format back into the previous formatting
For Each c In Target
Debug.Print "Adding " & c.NumberFormat & " to " & c.Address
m_numberFormatDictionary.Add c.Address, c.NumberFormat
Next c

'reset the range to what you just selected
Set m_previousRange = Target
End If

'simple prompt now, not sure what your use case is
If wasChange Then
MsgBox "There was at least one change!"
End If

End Sub

我不太确定您在寻找什么,您必须适当修改 print/msgbox 语句。根据您的用例,您可能需要稍微修改一下,但它适用于我的所有测试示例。

关于vba - 如何检测单元格格式的变化?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21342408/

33 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com