Search code examples
excelvbacell

Code run automatically on changing cell value in Excel


I am trying to run some VBA script to run automatically when I change a cell value automatically. I do have the script int he Worksheet and not a module. For some reason it is not working and I can't figure out why. Anyone have any idea why? Thanks so much!

Private Sub Worksheet_Change(ByVal Target As Range)

If Target = Range("B1") Then


r1 = Range("B1").Value
Range("A1").Value = 2 * r1

End If

End Sub

Solution

  • Consider:

    Private Sub Worksheet_Change(ByVal Target As Range)
        If Target.Address(0, 0) = "B1" Then
            Application.EnableEvents = False
            Range("A1").Value = 2 * Range("B1").Value
            Application.EnableEvents = True
        End If
    End Sub
    

    EDIT#1:

    If this fails to work, but does not produce an error message, you may need to re-enable Events . Put this in a standard module and run it:

    Sub EventsOn()
        Application.EnableEvents = True
    End Sub