This Excel VBA tutorial explains how to use Worksheet.Change Event.
You may also want to read:
Excel VBA get value before Worksheet_Change event
Excel automatically refresh pivot table
VBA Excel Worksheet_Change Event
Excel predefines some popular actions that you would do on different Objects (worksheet, workbook, button, etc), those actions are called Event. For example, activating a worksheet is an Event, closing a workbook is an Event, clicking on a button is an event. Each Object has its own list of Events, Workbook has a list of Events (e.g. close workbook, open workbook), worksheet has a list of Events (e.g. activate worksheet, edit a Cell).
If you perform an Event, say, closing a workbook, your desired code can be triggered. For example, you may want to save a workbook automatically when you close a workbook, or you may want a welcome message box to pop up when a workbook is opened. Event is a Sub Procedure (begin with Private Sub and end with End Sub) and is generated automatically (see in the below section) with a specific name, you can call a Sub Procedure or write your own code within the Event code.
Excel Worksheet_Change Event is an Event triggered when a you leave a Cell from edit mode (even no value is changed). For example, you double click on Cell A1 to enter edit mode, the event is triggered as you press “Enter” or click on any other Cell to exit the edit mode. Excel Worksheet_Change Event is not about value change of a Cell (of course the Event will trigger if you change a value), don’t be misled by the name.
If you want to know how to capture the initial value before change in order to compare the old and new value, read the below article
Excel VBA get value before Worksheet_Change event
How to insert Excel Worksheet_Change Event
Like all other worksheet events, you have to define the event and your desired actions within a specific worksheet where you want to Macro to trigger, each worksheet can have its own independent events.
1) Press Alt+F11 to enter into Visual Basic Editor
2) In the Project Explorer Window on the left, double click on the target worksheet
3) On top of the coding area, select “Worksheet” in the drop down box on the left, and then select “Change”.
4) Now you should be able to see two lines of code as below. Insert your action code between the two lines.
Example of Excel Worksheet_Change Event
For example, I want to prompt a message box if column A value >100.
Private Sub Worksheet_Change(ByVal Target As Range) If Target.Column = 1 And Target.Value > 100 Then MsgBox ("Column A value >100") End If End Sub
In the above code, “Target” is the Range you make a change. Target.Column = 1 bounds the checking to column A.
Trigger Macro when Value Changes
Below is a solution I copied and pasted from Microsoft Community that was answered by me.
Question
How can you instruct a macro to run when a certain cell changes?
For example, as soon as text in cell A1 changes, a macro is triggered.
Answer
Private Sub Worksheet_Change(ByVal Target As Range)
If Not Intersect(Target, Range("A1:B10")) Is Nothing Then
Dim OldValue As Variant
Application.EnableEvents = False
Application.Undo
OldValue = Target.Value
Application.Undo
Application.EnableEvents = True
If OldValue <> Target.Value Then
'Your Macro
End If
End If
End Sub
OR
Dim oldValue As Variant Private Sub Worksheet_SelectionChange(ByVal Target As Range) If Not Intersect(Target, Range("A1:B10")) Is Nothing Then oldValue = Target.Value End If End Sub Private Sub Worksheet_Change(ByVal Target As Range) If Not Intersect(Target, Range("A1:B10")) Is Nothing Then If Target.Value <> oldValue Then 'Do something End If End If End Sub
Outbound links
http://msdn.microsoft.com/en-us/library/office/ff839775%28v=office.15%29.aspx#AboutContributor
In this tutorial, we’ll discuss the Change
and ChangeSelection
worksheet events. The Worksheet_Change
event-handler procedure executes whenever any cell in the worksheet is changed and Worksheet_SelectionChange
event-handler procedure executes when the selection on the worksheet is changed.
The worksheet event-handler procedures must be in the code module for that worksheet. Put them somewhere else, and they won’t work. You can quickly access that code window by right-clicking the worksheet’s tab and selecting the View Code
:
Worksheet_Change event procedure
The Change
event triggers whenever any cell in the worksheet is changed. Excel uses the Worksheet_Change
event-handler procedure to trap the Change
event. The Worksheet_Change
procedure accepts Target
(the Range
object) as the parameter which represents the cell that was changed. The following example displays a message box that shows the address of the Target
range:
Private Sub Worksheet_Change(ByVal Target As Range) MsgBox Target.Address End Sub
Try making some changing in cells, every time you make changes, a message box displays the address of the cell that changed.
Monitor changes made to specific cell or range
The Worksheet_Chnage
procedure receives the Target
as Range
object which represents the changed cell(s). In this example, we compare the Target
with the given cell range A1:A10
using Intersect
method:
Private Sub Worksheet_Change(ByVal Target As Range) Dim MyRange As Range Set MyRange = Range("A1:A10") If Not Intersect(Target, MyRange) Is Nothing Then MsgBox ("You've changed the " & Target.Address) End If End Sub
A popup message box appears when a change made in the given cell range:
Worksheet_Change Vs. Worksheet_Calculate
The Worksheet_Change
event procedure is not executed by a calculation change, for example, when a formula returning a different value. You must use the Worksheet_Calculate
event procedure to capture the changes to values in cells that contain formulas.
Worksheet_SelectionChange event procedure
The Worksheet_SelectionChange
event procedure executes when a cell is selected. The following code highlights the active cell with a red color every time a different cell is selected:
Private Sub Worksheet_SelectionChange(ByVal Target As Range) Cells.Interior.ColorIndex = 0 Target.Interior.ColorIndex = 3 End Sub
The first statement removes the background color for all cells in the worksheet. Next, the the active cell is shaded with red color.
Take some action when specific cells or ranges selected
In many cases, you need to execute a piece of code when certain cells or ranges selected. To accomplish this, we use the Intersect
method on the Target
(selected cell or range) and the range containing the specific cell to verify the Target
is one of the specific cells or ranges. If the Target is in the range containing the specific cells, you can execute the code.
The following code highlights the active cell with a red color every time a different cell is selected:
Private Sub Worksheet_SelectionChange(ByVal Target As Range) Cells.Interior.ColorIndex = 0 Dim MyRange As Range Set MyRange = Range("A1:A10") If Not Intersect(Target, MyRange) Is Nothing Then Target.Interior.ColorIndex = 3 End If End Sub
by updated Apr 05, 2020
Automatically Run Excel Macros When a Cell Changes
VBA Change to a Single Cell
In Excel a Worksheet Change Event is a trigger for a macro when a cell or group of cells change. I will start out by showing how a change to a single cell can trigger an action. The following will colour cell B2 Red whenever the cell changes. The following uses the(ByVal Target As Range) line which uses the Variable named Target. The Target is the Range which will trigger an action. You assign the Range within the code itself.
The following YouTube video takes you the cell change event, both a single cell and multiple cells. The following Excel file goes with the video.
Change Cell.xlsm
Before you fill your boots with the following it is worth mentioning that when you employ the use of the VBA change events you lose the ability to undo in Excel. Normally Excel keeps a record of a number of actions.
The VBA code to perform this action needs to go in the sheet object you want to perform the event. If you wanted to put the code in Sheet1 then you would double click on the sheet you wish to run the code from.
The following is an example of Excel VBA coding you could put in Sheet1 or any of the other sheet objects.
In the example above you need to keep the $ (absolute sign) or the code will not work. So when referencing a single cell the range reference needs to be absolute.
«$B$2”
The following VBA performs the same action as the above example. It is a little more flexible if you wish to add to the range. Once Inside the Worksheet Change Event, if the Target falls within the defined Range and the cell contents change, it will trigger an action inside VBA.
Option Explicit
Private Sub Worksheet_Change(ByVal Target As Range) ‘Excel VBA with more cells in the range.
If Not Intersect(Target, Range(«B2»)) Is Nothing Then
Target.EntireRow.Interior.ColorIndex=15
End If
End Sub
Disable Events
Occasionally one of the things you may wish to do with the cell that is changing is delete, copy, cut or some other action which triggers a circular loop. For example, if you wanted to move a line to another sheet which met a condition, when the condition was met you would trigger the Change Event and when you deleted the row you would start another change event. This second change event would cause a debug error. To get around this you can turn Events off at the start of the procedure and turn them back on at the end of the procedure.
The line of code is;
Application.EnableEvents=False
and the following is an example of how it might be used.
Private Sub Worksheet_Change(ByVal Target As Range) ‘Excel VBA change event test for close.
If Not Intersect(Target, Range(«A2», Range(«A» & Rows.Count).End(xlUp))) Is Nothing Then
Application.EnableEvents=False
If Target=»Closed» Then
Target.EntireRow.Copy Sheet2.Range(«A1»).End(xlDown)(2)
Target.EntireRow.Delete
End If
End If
Application.EnableEvents=True
End Sub
The VBA macro will copy the entire row from one sheet to another and delete the row which was just copied. The example is shown in the file below.
VBA Worksheet Change Event Multiple Cells
When we want to perform an action when more than one cell is changed we can use the following VBA code to change a larger range. It focuses on shifting the range within the Target. The following is an example of a change event where if the cells from A2:A10 change the procedure will trigger an action.
Option Explicit ‘Excel worksheet change event Range A1 to A10
Private Sub Worksheet_Change(ByVal Target As Range)
If Not Intersect(Target, Range(«A2:A10»)) Is Nothing Then
Target.EntireRow.Interior.ColorIndex=15
End If
End Sub
VBA Double Click Event
A double click event in Excel VBA is self explanatory. It will occur on double click of a cell in the Target range. So if you have a range between C13 and O26 where you want to perform an action on Double click, the following should help.
‘Excel worksheet double click change event Range C13 to O26
Private Sub Worksheet_BeforeDoubleClick(ByVal Target As Range, Cancel As Boolean)
If Not Intersect(Target, Range(«C13:O26»)) Is Nothing Then
Target.Value=ActiveCell.Offset(19, 0).Value
End If
End Sub
VBA Before Save Event
This event is triggered as the name suggests before each Save. So as the save Excel file icon is clicked the code which is associated with this event will trigger.
The before Save event needs to go into the ThisWorkbook Object in order for it to run.
The following Excel VBA macro will put the word False in Cell A1 before the file is saved.
Option Explicit
Private Sub Workbook_BeforeSave(ByVal SaveAsUI As Boolean, Cancel As Boolean)
Sheet1.Cells(1, 1)=False
End Sub
Worksheet Change Event in VBA and Preventing Event Loops
Related Links:
Excel VBA Events, Event Handlers, Trigger a VBA Macro.
Worksheet Selection Change Event, Excel VBA.
————————————————————————
Contents:
Worksheet_Change Event
Preventing Event Loops with Application.EnableEvents = False
————————————————————————
Worksheet_Change Event:
You can auto run a VBA code, when content of a worksheet cell changes, with the Worksheet_Change event. The change event occurs when cells on the worksheet are changed either by the user, or by any VBA application or by an external link, but not when a cell changes due to recalculation as a result from formula or due to format change. For changes made by calculation, use Worksheet_Calculate event.
Worksheet change procedure is installed with the worksheet, ie. it must be placed in the code module of the appropriate Sheet object. To create a worksheet change event: use the Visual Basic Editor -> in the Project Explorer, double click on the appropriate sheet (under ‘Microsoft Excel Objects’ which is under the VBAProject/name of your workbook) -> in the Code window, select «Worksheet» from the left-side «General» drop-down menu and then select «Change» from the right-side «Declarations» drop-down menu. You will get a procedure «shell» in the code window as follows:
Private Sub Worksheet_Change(ByVal Target As Range)
End Sub
Target is a parameter of data type Range (ie. Target is a Range Object). It refers to the changed Range and can consist of one or multiple cells. If Target is in the defined Range, and its value or content changes, it will trigger the vba procedure. If Target is not in the defined Range, nothing will happen in the worksheet. In this manner, you can limit the events to a particular range for both the Change and SelectionChange events. This can be done in multiple ways:
Using Target Address. Trigger the procedure, if a single cell (A5) value is changed:
If Target.Address = «$A$5» Then MsgBox «Success»
If Target.Address = Range(«$A$5»).Address Then MsgBox «Success»
If Target.Address = Range(«A5»).Address Then MsgBox «Success»
Using Target Address. If cell (A1) or cell (A3) value is changed:
If Target.Address = «$A$1» Or Target.Address = «$A$3» Then MsgBox «Success»
Using Target Address. If any cell(s) value other than that of cell (A1) is changed:
If Target.Address <> «$A$1» Then MsgBox «Success»
The following use of Target.Address is not correct, and the code will not run:
If Target.Address = «$a$5» Then MsgBox «Success»
If Target.Address = «A1» Then MsgBox «Success»
If Target.Address = «$A$1:$A$10» Then MsgBox «Success»
If Target.Address = Range(«$A$1:$A$10») Then MsgBox «Success»
Note: Target.Address should be an absolute reference [unless used as Range(«A5»).Address — see above] and in Caps. Use this to run code when content of a single cell is changed or when any cell(s) other than a specific cell is changed.
Trigger the procedure, if any cell in a column(s) is changed, say for any change in a cell in column B or column C:
If Target.Column = 2 Or Target.Column = 3 Then MsgBox «Success»
Intersect method for a single cell. If Target intersects with the defined Range of A1 ie. if cell (A1) value is changed, the code is triggerred:
If Not Application.Intersect(Target, Range(«A1»)) Is Nothing Then MsgBox «Success»
Trigger the procedure, if at least one cell of Target is A1,B2,C3:
If Not Application.Intersect(Target, Range(«A1,B2,C3»)) Is Nothing Then MsgBox «Success»
At least one cell of Target is within the range C5:D25:
If Not Application.Intersect(Target, Me.Range(«C5:D25»)) Is Nothing Then MsgBox «Success»
If you want the code to run when only a single cell in Range(«C1:C10») is changed and do nothing if multiple cells are changed:
Private Sub Worksheet_Change(ByVal Target As Range)
If Intersect(Target, Range(«C1:C10»)) Is Nothing Or Target.Cells.Count > 1 Then
Exit Sub
Else
MsgBox «Success»
End If
End Sub
Preventing Event Loops with Application.EnableEvents = False
Example of a recursive loop code:
Private Sub Worksheet_Change(ByVal Target As Range)
If Not Application.Intersect(Target, Range(«A1:A10»)) Is Nothing Then
Range(«A5»).Value = Range(«A5»).Value + 1
End If
End Sub
Recursive Event Loop:
If, at each runtime, the worksheet_change event changes the content of a cell which itself is part of the Target Range (ie. which triggers the change event), it will result in reprocessing the change event repeatedly. Recursion is the process of repeating in a similar way viz. when the procedure calls itself. Refer to above example of a recursive loop code, if any cell content in Range(«A1:A10») is changed by the user, the cell A5 value will change and increment by 1; this will again trigger the change event [because of change in value of cell A5 which is in the Target Range(«A1:A10»)] and will in turn change the cell A5 value by incrementing it by 1; and then this change in cell A5 will again trigger the change event and change the cell A5 value by incrementing it by 1; and so on. This will result in a recursive loop which might result in a ‘Out Of Stack Space’ untrappable error, or depending on the Excel setting, the loop might terminate at a threshold limit of say 100. To prevent this, enter the following at the beginning of the code: Application.EnableEvents = False. This means that any change made by the VBA code will not trigger any event and will not enable restarting the worksheet_change event. EnableEvents is not automatically changed back to True, this should be specifically done in your code, by adding the following line at the end of the code: Application.EnableEvents = True. Meanwhile, if during runtime, your code encounters an error, you will need an ErrorHandler (to change EnableEvents back to True) because events have been disabled in the beginning of the code. This can be done as follows.
ErrorHandler, Example 1:
Private Sub Worksheet_Change(ByVal Target As Range)
‘on the occurrence of an error procedure flow is directed to the error-handling routine (ie. ErrHandler) which handles the error
On Error GoTo ErrorHandler
‘to prevent recursion — so that any change made by code will not trigger an event to restart the Worksheet_Change event
Application.EnableEvents = False
‘on changing cell A1 or B1, go to ErrorHandler which reverts EnableEvents to True & then exit sub
If Target.Address = «$A$1» Or Target.Address = «$B$1» Then GoTo ErrorHandler
‘if value of any cell in column 1 or 2 is changed
If Target.Column = 1 Or Target.Column = 2 Then
‘if changed cell value is numeric ie. new value is not text
If IsNumeric(Target) Then
‘increment cell B2 value by 1
Range(«B2»).Value = Range(«B2»).Value + 1
End If
End If
‘EnableEvents is not automatically changed back to True & hence this needs to be done specifically at the end of the code before exit.
‘because an exit statement (ex. Exit Sub) is not placed above, the error-handling routine will also execute when there is no error.
ErrorHandler:
Application.EnableEvents = True
End Sub
ErrorHandler, Example 2:
Private Sub Worksheet_Change(ByVal Target As Range)
On Error Resume Next ‘skip all run-time errors
If Target.Address = «$A$1» Or Target.Address = «$B$1» Then Exit Sub
Application.EnableEvents = False
If Target.Column = 1 Or Target.Column = 2 Then
If IsNumeric(Target) Then
Range(«B2»).Value = Range(«B2»).Value + 1
End If
End If
Application.EnableEvents = True
On Error GoTo 0 ‘Turn off error trapping and re-allow run time errors
End Sub
On Error Statements explained:
On Error Resume Next: Specifies that when a run-time error occurs, control goes to the statement immediately following the statement where the error occurred, and execution continues from that point.
The On Error GoTo 0 statement turns off error trapping. It disables enabled error handler in the current procedure and resets it to Nothing.
On Error GoTo Line: Enables the error-handling routine that starts at the specified Line. The On Error GoTo statement traps all errors, regardless of the exception class.