Run code when a cell changes or a workbook opens
Dialogs, functions and events9 minPremium
Builds on Point at cells with Range, Cells, Offset and CurrentRegion and Make decisions with If and Select Case.
The front desk of a conference center in Tampere tracks room bookings in a shared workbook. When someone changes a booking's status in column C, the team wants the date and time of the change in column D, without anyone pressing a button.
How it works
An event is something that happens in Excel: a workbook opens, a cell changes, a sheet is activated. An event procedure runs by itself when its event happens.
Event procedures live in the module of the object they belong to. A sheet's events go in that sheet's module: double-click the sheet in the Project Explorer, choose Worksheet in the list at the top left of the code window, then the event in the list at the top right. The editor writes the first and last lines for you, with the exact name VBA looks for. Choosing Worksheet also adds an empty Worksheet_SelectionChange, which you can delete. Workbook events, such as Workbook_Open, go in ThisWorkbook.
Worksheet_Change runs after someone changes cells on that sheet, and Target is the range they changed. It doesn't run when a formula's result changes on recalculation.
Example
Private Sub Worksheet_Change(ByVal Target As Range)Dim changed As RangeSet changed = Intersect(Target, Range( "C2:C500")) If changed Is Nothing Then Exit SubApplication.EnableEvents = False changed.Offset( 0, 1). Value = Now Application.EnableEvents = True End Sub
Intersect gives the part of Target inside C2:C500, or Nothing when the change was somewhere else, and the procedure stops there. Writing the time is a change too, so events are switched off while the procedure writes, and back on after.
Event code runs only when the workbook's macros are enabled, as with any macro.
Common mistakes
- Event code in Module1. It never runs; put it in the sheet's module or in ThisWorkbook.
- A name typed by hand with a slip, such as
Worksheet_Changed. VBA only runs a procedure whose name matches the event exactly, so pick it from the two lists. - Leaving events off. If an error stops the procedure between the two
EnableEventslines, events stay off for every workbook until you set it back to True or restart Excel.
In short
- An event procedure runs by itself:
Worksheet_Changein a sheet's module,Workbook_Openin ThisWorkbook. - Use
IntersectwithTargetto react only to the cells you care about. - Turn events off while the procedure writes to the sheet, and back on after.
Practice
Premium4 exercises: 2 macros, 1 quiz question and 1 set of steps.
Practice is part of Premium
Every lesson is free to read, and you can practice the free lessons without an account. This lesson's exercises are part of Premium, which you add to a free account.
Have one? Sign in