VBA: Run a Macro When a Cell Changes

September 13th, 2004 | Categories: VBA | Tags:

You may want to run a macro when a cell changes. A popular use of this ability is to have custom code validate a cell after a change is made. It’s easy to do this by using the worksheet objects change event.

In the Visual Basic Editor you must first double click the sheet name where the cell changes that activates the macro. This opens the code window for that sheet object. In this case I wanted to run a macro when a cell in Sheet1 changes.

CellChange1

After opening the code window for the Worksheet you place your code in the Worksheet_Change event. The following example will display a message box if the contents of cell A1 change. First the subroutine fires if any cell changes, then the use of an IF..Then statement will run the code only if cell A1 was the cell that changed based on the If…Then.

Private Sub Worksheet_Change(ByVal Target As Range)

If Target.Address = "$A$1" Then
     MsgBox "This Code Runs When Cell A1 Changes!"
End If

End Sub

You can place your code directly in the Worksheet_Change subroutine or call another macro from there.

  1. Aaron
    September 16th, 2008 at 22:46
    Reply | Quote | #1

    I was wondering if this could be changed so that if a value in a specific range changed it would have the same effect.

    Thanks!

  2. Mark
    September 27th, 2008 at 13:29
    Reply | Quote | #2

    I am using this to validate the entry into a cell. Is it possible to save the previous value of the cell in order to reinstate it should the new value be invalid?

    Thanks in advance for your help

    Mark