VBA course · Lesson 20 of 33
Events: macros that run by themselves
Make VBA react automatically with Worksheet_Change, SelectionChange, BeforeDoubleClick, Workbook_Open and BeforeSave, and use EnableEvents safely.
Every macro so far ran because someone started it: from the Macros dialog, a button or a shortcut. Event procedures run by themselves when something happens in Excel: a cell is changed, a sheet is activated, the workbook is opened or about to be saved. With events you can add a timestamp the moment a status becomes "Done", stop people saving a workbook with missing data, or refresh a report whenever its sheet is shown.
Events are powerful, and because they fire without anyone pressing a button, a mistake in an event procedure can be very confusing. This lesson shows how to write them so they stay fast and safe.
Where event code lives
Event procedures are not written in a standard module. They go into the module of the object that raises the event:
- Sheet modules (
Sheet1 (Sales),Sheet2 (Staff)and so on in the Project Explorer) hold events for that one worksheet, such asWorksheet_Change. - The ThisWorkbook module holds events for the whole workbook, such as
Workbook_Open,Workbook_BeforeSave, andWorkbook_SheetChange(which fires for every sheet).
The easiest way to create an event procedure with the exact right name and parameters is to let the editor do it:
- Double-click the sheet (or
ThisWorkbook) in the Project Explorer to open its module. - In the left drop-down at the top of the code window choose Worksheet (or Workbook).
- In the right drop-down choose the event, e.g. Change. The editor inserts an empty procedure.
The name must be exactly right. A procedure called Worksheet_Changed or placed in a standard module is just a normal macro that never runs by itself. A quick shortcut on Windows: right-click a sheet tab and choose View Code to jump to that sheet's module.
Worksheet_Change: reacting to edits
Worksheet_Change fires after one or more cells on the sheet are changed by the user or by code. Its parameter Target is the range that changed. Here is a classic: a task list where entering "Done" in the Status column writes the completion date next to it.
| A | B | C | D | |
|---|---|---|---|---|
| 1 | Task | Owner | Status | Completed |
| 2 | Send Q3 invoices | Ana | Open | |
| 3 | Update price list | Ben | Open | |
| 4 | Payroll check | Chloe | Done | 2026-11-28 |
Before: the Tasks sheet
Option Explicit
Private Sub Worksheet_Change(ByVal Target As Range)
Dim changed As Range
Dim c As Range
' Only react to cells in C2:C1000
Set changed = Intersect(Target, Me.Range("C2:C1000"))
If changed Is Nothing Then Exit Sub
On Error GoTo SafeExit
Application.EnableEvents = False ' our own writes must not trigger this event again
For Each c In changed.Cells
If LCase(Trim(c.Value)) = "done" Then
If IsEmpty(c.Offset(0, 1).Value) Then
c.Offset(0, 1).Value = Date
End If
Else
c.Offset(0, 1).ClearContents
End If
Next c
SafeExit:
Application.EnableEvents = True
End Sub| A | B | C | D | |
|---|---|---|---|---|
| 1 | Task | Owner | Status | Completed |
| 2 | Send Q3 invoices | Ana | Done | 2026-12-02 |
| 3 | Update price list | Ben | Open | |
| 4 | Payroll check | Chloe | Done | 2026-11-28 |
After typing Done in C2 on 2 December 2026
This short procedure contains four habits that every Change event should have:
- Filter with Intersect.
Intersect(Target, Me.Range("C2:C1000"))returns the part ofTargetinside the watched area, orNothingif there is no overlap. Leaving immediately when the change is elsewhere keeps the workbook fast.Memeans "this sheet" inside a sheet module. - Handle several cells.
Targetis not always one cell. Users paste blocks, fill down or press Delete on a selection. Looping throughchanged.Cellshandles all of them. Code likeIf Target.Value = "Done"crashes with a type mismatch whenTargethas several cells. - Turn events off while writing. Writing the date is itself a change on the sheet, so it would trigger
Worksheet_Changeagain, which could write again, and so on.Application.EnableEvents = Falsestops that. - Always turn events back on. If an error occurs while events are off and the macro stops, events stay off for the whole Excel session and none of your event code works any more. The
On Error GoTo SafeExitline makes sureEnableEvents = Trueruns whatever happens. See Error handling and debugging in VBA.
Date writes a date only. Use Now for date and time, and format the column as you like.
Application.EnableEvents = True and press Enter.What does not trigger Change
Worksheet_Change does not fire when a formula result changes because of recalculation (use Worksheet_Calculate for that), when only formatting changes, or when rows are sorted in some cases. It does fire when a cell is cleared, even if it was already empty, and when your own code writes to the sheet.
Validating input in Change
Events are useful to enforce rules that data validation cannot express. This one rejects discounts above 15% for anyone except the sales manager, and undoes the entry:
Option Explicit
Private Sub Worksheet_Change(ByVal Target As Range)
Dim c As Range
If Intersect(Target, Me.Range("F2:F500")) Is Nothing Then Exit Sub
If Target.Cells.Count > 1 Then Exit Sub ' keep the example simple
Set c = Target
If IsNumeric(c.Value) And Not IsEmpty(c.Value) Then
If c.Value > 0.15 And Environ$("USERNAME") <> "mgr.sales" Then
On Error GoTo SafeExit
Application.EnableEvents = False
Application.Undo ' restore the previous value
MsgBox "Discounts above 15% need the sales manager.", vbExclamation
End If
End If
SafeExit:
Application.EnableEvents = True
End SubApplication.Undo reverses the user's last edit, which is exactly what you want here. It only works as the first thing your code changes; once your macro has modified the sheet, the undo list is gone. Environ$("USERNAME") returns the Windows login name. On a Mac use Environ$("USER"), or better Application.UserName, which works on both but is easy to change in Excel's options.
SelectionChange and BeforeDoubleClick
Worksheet_SelectionChange fires whenever the selection moves. Use it sparingly because it runs constantly, but it is nice for small helpers, such as showing the full comment of a row in the status bar:
Option Explicit
Private Sub Worksheet_SelectionChange(ByVal Target As Range)
If Target.Row < 2 Or Target.Cells.Count > 1 Then
Application.StatusBar = False ' give the status bar back to Excel
Exit Sub
End If
Application.StatusBar = Me.Cells(Target.Row, "A").Value & _
": credit limit " & Format(Me.Cells(Target.Row, "E").Value, "#,##0")
End SubWorksheet_BeforeDoubleClick fires before Excel's own double-click action (entering edit mode). Setting the Cancel parameter to True cancels Excel's action. Here a double-click in the Paid column toggles a tick mark:
Option Explicit
Private Sub Worksheet_BeforeDoubleClick(ByVal Target As Range, Cancel As Boolean)
If Intersect(Target, Me.Range("G2:G500")) Is Nothing Then Exit Sub
Cancel = True ' do not enter edit mode
On Error GoTo SafeExit
Application.EnableEvents = False
If Target.Value = "Yes" Then
Target.Value = ""
Else
Target.Value = "Yes"
End If
SafeExit:
Application.EnableEvents = True
End SubOther useful sheet events are Worksheet_Activate (the sheet is shown, e.g. refresh a summary), Worksheet_Deactivate, Worksheet_Calculate and Worksheet_BeforeRightClick.
Workbook events
Workbook events go in the ThisWorkbook module.
Workbook_Open
Runs when the workbook opens with macros enabled. Typical uses: go to the start sheet, show today's reminders, refresh data.
Option Explicit
Private Sub Workbook_Open()
Dim overdue As Long
Me.Worksheets("Dashboard").Activate
overdue = Application.WorksheetFunction.CountIfs( _
Me.Worksheets("Invoices").Range("E:E"), "<" & CLng(Date), _
Me.Worksheets("Invoices").Range("F:F"), "<>Paid")
If overdue > 0 Then
MsgBox overdue & " invoice(s) are overdue.", vbInformation, "Reminder"
End If
End SubInside ThisWorkbook, Me is the workbook itself. Note CLng(Date): a criterion like "<" & Date would turn the date into text in your regional format, which COUNTIFS may misread; the serial number is unambiguous. Holding Shift while opening the file from Excel's Open dialog skips Workbook_Open on Windows, which is handy when the event code is broken.
Workbook_BeforeSave and BeforeClose
Workbook_BeforeSave runs just before saving. Setting Cancel = True stops the save. Use it to check required data:
Option Explicit
Private Sub Workbook_BeforeSave(ByVal SaveAsUI As Boolean, Cancel As Boolean)
Dim ws As Worksheet
Dim lastRow As Long
Dim r As Long
Set ws = Me.Worksheets("Orders")
lastRow = ws.Cells(ws.Rows.Count, "A").End(xlUp).Row
For r = 2 To lastRow
If Len(Trim(ws.Cells(r, "B").Value)) = 0 Then
MsgBox "Order " & ws.Cells(r, "A").Value & " has no customer. Please fill in B" & r & ".", vbExclamation
ws.Activate
ws.Cells(r, "B").Select
Cancel = True
Exit Sub
End If
Next r
End SubSaveAsUI is True when the Save As dialog is about to appear. Workbook_BeforeClose(Cancel As Boolean) works the same way for closing. Be careful with BeforeClose: if the user then chooses not to save, your changes made in the event are lost, and if you save inside it the user loses the choice. Keep it simple.
Workbook_SheetChange: one event for all sheets
Workbook_SheetChange(ByVal Sh As Object, ByVal Target As Range) fires for a change on any sheet, with Sh telling you which. It is ideal for a "last modified" stamp on every month sheet without copying the same code into twelve sheet modules:
Option Explicit
Private Sub Workbook_SheetChange(ByVal Sh As Object, ByVal Target As Range)
If Not Sh.Name Like "####-##" Then Exit Sub ' only sheets named like 2026-11
On Error GoTo SafeExit
Application.EnableEvents = False
Sh.Range("H1").Value = "Last change: " & Format(Now, "yyyy-mm-dd hh:nn") & " by " & Application.UserName
SafeExit:
Application.EnableEvents = True
End SubEvents and users
Event code only runs when macros are enabled, so never rely on it for anything security-critical; a user who opens the file with macros disabled bypasses it. Changes made by event code also clear Excel's undo list, which some users find annoying: after a Change event writes a timestamp, Ctrl+Z (Cmd+Z) no longer undoes their last typing. Keep event code short and quick, because it runs very often.
Environ$("USERNAME") (use Environ$("USER")), and ActiveX control events do not exist because Mac Excel has no ActiveX controls. UserForm events are covered in UserForms: build a data-entry form in VBA.Common mistakes
- Putting event code in a standard module, or misspelling the name: it never runs.
- Forgetting
EnableEvents = Falsebefore writing to the sheet insideWorksheet_Change: an endless chain of events, ending in "Out of stack space". - Turning events off without an error-safe way back on: all events silently stop.
- Treating
Targetas a single cell: pasting a block causes Type mismatch. - No
Intersectfilter: the code runs (and slows Excel) on every single edit anywhere on the sheet. - Heavy work in
SelectionChange: the sheet feels sluggish every time the cursor moves.
Check yourself
1. Where must the Worksheet_Change procedure for the Sales sheet be written?
Sheet events belong in the module of that sheet; workbook events go in ThisWorkbook.
2. Why set Application.EnableEvents = False before writing to the sheet inside Worksheet_Change?
Writing a cell is itself a change; without disabling events the procedure calls itself again and again.
3. What does Intersect(Target, Me.Range("C2:C100")) return when the user edited E5?
There is no overlap, so Intersect returns Nothing and the code can exit early.
4. In Workbook_BeforeSave, how do you stop the save?
The Cancel parameter tells Excel to abort the save after the event procedure ends.
5. Your event code stopped working after a crash. What is the most likely cause?
An error between disabling and re-enabling events leaves them off for the session; turn them back on in the Immediate window and add an error-safe reset.