Home » excel » excel – Trigger macro with change in different worksheet

excel – Trigger macro with change in different worksheet

Posted by: admin May 14, 2020 Leave a comment

Questions:

Apologies any incorrect terms, this is the first time I am trying to code a macro. I currently have the following code running:

Private Sub Worksheet_Deactivate()
'Alpha Show / Hide
If Sheets("Project_selection").Range("D4") = Range("C2") Then
    Sheet3.EnableCalculation = True
ElseIf Sheets("Project_selection").Range("D4") = "All" Then
    Sheet3.EnableCalculation = True
    Else
        Sheet3.EnableCalculation = False
End If
End Sub

which has been cobbled together from other codes and google. It works, but only when I move out of the sheet, which I think is being driven by the first line.

I would actually like it to activate when the Cell D4 in the ‘Project_selection’ sheet (a separate sheet to the one the code is on) gets changed – does anyone know how I would do that? I have seen references to worksheet_change, but I do not understand how one defines the target/range to get the appropriate reference.

Hope that makes sense and thanks in advance!

How to&Answers:

If you were to place the following code under the sheet (Project_selection), it would fire that event every time a change has happened in Cell D4:

Private Sub Worksheet_Change(ByVal Target As Range)
Dim ws As Worksheet: Set ws = Sheets("Project_selection")
    If Target.Address = "$D$4" Then
        If ws.Range("D4") = ws.Range("C2") Then
            Sheet3.EnableCalculation = True
        ElseIf ws.Range("D4") = "All" Then
            Sheet3.EnableCalculation = True
        Else
            Sheet3.EnableCalculation = False
        End If
    End If
End Sub