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

sig*_*gil 7 excel vba excel-vba

我想在Excel工作表中嵌入一个过程,该过程将检测单元格格式何时更改,例如从Text到Number.

但我无法弄清楚如何获得单元格的格式类型.我尝试使用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
Run Code Online (Sandbox Code Playgroud)

但是有了这个代码,如果我将单元格A1的数据类型从Number更改为Text,Worksheet_Change则不会触发; 只有在我更改单元格的内容时才会调用事件处理程序.

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

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

end*_*and 2

好问题!

如果您只想触发 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
Run Code Online (Sandbox Code Playgroud)

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