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

后端 未结 4 976
清酒与你
清酒与你 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:21

    The code you used does not work because the cell changing is not the cell with the formula but the sell... being changed :)

    Here is what you shoud add to the worksheet's module:

    (Udated: The line "Set rDependents = Target.Dependents" will rase an Error if there are no dependents. This update takes care of this.)

    Private Sub Worksheet_Change(ByVal Target As Range)
        Dim rDependents As Range
    
        On Error Resume Next
        Set rDependents = Target.Dependents
        If Err.Number > 0 Then
            Exit Sub
        End If
        ' If the cell with the formula is "F160", for example...
        If Not Application.Intersect(rDependents, Range("F160")) Is Nothing Then
            Call abc
        End If
    End Sub
    
    Private Sub abc()
        MsgBox """abc()"" is running now"
    End Sub
    

    You can expand this if there are many dependent cells by seting up an array of cell addresses in question. Then you would test for each address in the array (you can use any looping structure for this) and ran a desited subroutine correcponding to the changed cell (use SELECT CASE...) for this.

提交回复
热议问题