Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

VBA trigger macro on cell value change

This should be simple. When the value of a cell changes I want to trigger some VBA code. The cell (D3) is a calculation from two other cells =B3*C3. I have attempted 2 approaches:

Private Sub Worksheet_Change(ByVal Target As Range)
  If Target.Column = 4 And Target.Row = 3 Then
    MsgBox "There was a change in cell D3"
  End If
End Sub

Since the cell is a calculation this is not triggered when the value changes, because the calculation remains the same. I also tried:

Private Sub Worksheet_Calculate()
  MsgBox "There was a calculation"
End Sub

But I have multiple calculations on the sheet and it triggers multiple times. Is there a way I can identify which calculation changed on the calculation event? Or is there another way I can track when D3 changes?

like image 694
Kyle Weller Avatar asked Aug 29 '13 00:08

Kyle Weller


People also ask

How do you trigger a macro when a cell value changes?

Run Macro When a Cell Changes (Method 1)Go to the VBA Editor (Alt + F11) and double-click the name of the spreadsheet that contains the cell that will change or just right-click the worksheet tab and click View Code.

Can VBA function change cell values?

Despite what others say, it is possible to change another cell with a VBA user-defined function.


2 Answers

Could you try something like this? Change the formula to =D3AlertOnChange(B3*C3).

Private D3OldVal As Variant

Public Function D3AlertOnChange(val)
    If val <> D3OldVal Then MsgBox "Value changed!"
    D3OldVal = val
    D3AlertOnChange = val
End Function
like image 143
Chel Avatar answered Oct 03 '22 15:10

Chel


Or try

Private Sub Worksheet_Change(ByVal Target As Range)
Dim numdependences As Integer
On Error Resume Next
HasDependents = Target.Dependents.Count
If Err = 0 Then
    If InStr(Target.Dependents.Address, "$D$3") <> 0 Then
        MsgBox "change"
    End If
End If
On Error GoTo 0
End Sub

You need the error control in case you change a cell that has not dependents.

like image 22
Diego Avatar answered Oct 03 '22 14:10

Diego