How can I run VBA code each time a cell gets its value changed by a formula?

后端 未结 4 970
清酒与你
清酒与你 2020-11-28 10:46

How can I run a VBA function each time a cell gets its value changed by a formula?

I\'ve managed to run code when a cell gets its value changed by the user, but it d

4条回答
  •  时光取名叫无心
    2020-11-28 11:31

    Here is another way using classes. The class can store cell Initial value and cell address. On calculate event it will compare the address current value with the stored initial value. Example below is made to listen to one cell only ("A2"), but you can initiate listening to more cells in the module or change the class to work with wider ranges.

    Class module called "Class1":

    Public WithEvents MySheet As Worksheet
    Public MyRange As Range
    Public MyIniVal As Variant
    
    Public Sub Initialize_MySheet(Sh As Worksheet, Ran As Range)
        Set MySheet = Sh
        Set MyRange = Ran
        MyIniVal = Ran.Value
    End Sub
    Private Sub MySheet_Calculate()
    
    If MyRange.Value <> MyIniVal Then
        Debug.Print MyRange.Address & " was changed from " & MyIniVal & " to " & MyRange.Value
        StartClass
    End If
    
    End Sub
    

    Initialize the class in normall module.

    Dim MyClass As Class1
    
    Sub StartClass()
    Set MyClass = Nothing
    Set MyClass = New Class1
    MyClass.Initialize_MySheet ActiveSheet, Range("A2")
    End Sub
    

提交回复
热议问题