Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Execute macro only if specific cell value changes

I have a simple countif formula in Cell E2 that will check for a specific text. Once it's true, it'll execute a macro that will prompt for a msgbox. This code works fine, but when making any other changes to the worksheet will execute the macro again, even though Cell E2's value hasn't changed. How do I stop the macro from executing any further if E2 does not change at all?

Sub Worksheet_Change(ByVal Target As Range)

If Not Intersect(Target, Range("E2")) Is Nothing Then
    If Target.Value = "True" Then
        Application.EnableEvents = False
        a = MsgBox("Test", vbYesNo, "Test")
        If a = vbYes Then
            Range("E3") = "003"
        Else
            Range("E3") = "001"
        End If

        Call ApplyMG
        Application.EnableEvents = True
    End If
End If
End Sub 

EDIT: Thanks to the comment below, removed 'old code' setting target to the same range in the intersect line. However, the macro is not being triggered anymore.

like image 636
Basher Avatar asked Apr 24 '26 22:04

Basher


1 Answers

Well turns out I was overcomplicating things. After some research, what I'm trying to do won't work on Worksheet_Change in the first place as this is a formula. So, I only need to move my code onto Worksheet_Calculate instead. No need for unnecessary intersect or anything, as my code only needs to determine if Cell E2 is True, which is determined by the cell formula. Nothing else would matter anyway.

Private Sub Worksheet_Calculate()
Dim trigger As Range
Set trigger = Range("E2")

If trigger.Value = "True" Then
    Application.EnableEvents = False
    a = MsgBox("Test", vbYesNo, "Test")
    If a = vbYes Then
        Range("E3") = "003"
    Else
        Range("E3") = "001"
    End If

    Call ApplyMG
    Application.EnableEvents = True
End If
End Sub
like image 173
Basher Avatar answered Apr 26 '26 11:04

Basher