Richard
Richard

Reputation: 11

execute macro when cell value changes due to another macro

I have a sheet with two buttons. One button places a value in a cell (E2) and the other button counts that value (in E2) down by 1 every time it is pushed. I want the value in E2 cell to dictate the color of D2, such that D2 is Red whenever the value of the cell is > 0 and green when it is =< 0.

Here are my two buttons:

Button 1

Sub Use2()
     Range("e2").Value = Range("d2")
End Sub

Button 2

Sub Subtract1()
     Range("E2").Value = Range("E2").Value - 1
End Sub

I added this code:

Private Sub Worksheet_Change(ByVal Target As Range)
    If Target.Address = Range("E2").Address and Target.Value >0 Then
      Range("D2").Interior.Color = vbRed
  End If
End Sub

I didn't even get to the green part because this only works if I manually enter a value greater than 0 in E2. It doesn't work if the value of E2 changes to a value > 0 by pushing button 1. Can anyone help me change this so it works. Thanks!

Upvotes: 1

Views: 2171

Answers (2)

David Zemens
David Zemens

Reputation: 53623

In addition to @Santosh's comments about Enable/Disable Events during runtime of event macros, assuming your subroutines are all in the Worksheet code module, you can simply force a call to the _Change event like so:

Sub Use2()
    Range("E2").Value = Range("E2")
    Worksheet_Change Range("E2")
End Sub

Sub Subtract1()
    Range("E2").Value = Range("E2").Value - 1
    Worksheet_Change Range("E2")
End Sub

Upvotes: 0

Santosh
Santosh

Reputation: 12353

Whenever usingWorksheet_Change event

1) Use Application.EnableEvents to prevent Events from firing when other code is running.

2) Use Error Handling so that EnableEvents is set to True

Private Sub Worksheet_Change(ByVal Target As Range)
    Application.EnableEvents = False

    On Error Resume Next

    If Not Intersect(Range("E2"), Target) Is Nothing Then

        If Target.Value > 0 Then
            Range("D2").Interior.Color = vbRed
        Else
            Range("D2").Interior.Color = vbGreen
        End If
    End If

    Application.EnableEvents = True
End Sub

It can also be achieved using Conditional Formatting.

enter image description here

Upvotes: 1

Related Questions