Excel VBA events: run macros automatically when cells change

Nobody starts an event macro with a button. Excel calls it itself as soon as something happens: a cell changes, a sheet is activated, the file opens. That is how you stamp a date automatically, turn entries into capitals or check them on the spot.

In short: Private Sub Worksheet_Change(ByVal Target As Range) in the worksheet's code window runs after every change on that sheet, and Target is the changed cell. If Not Intersect(Target, Range("B:B")) Is Nothing Then reacts to column B only. If the macro writes to the sheet itself, put Application.EnableEvents = False before it and = True after.

What you need to know: Offset, dates and debugging.

Try it right now

In the stockroom, the delivered quantity gets entered and the date should appear next to it automatically. The exercise replays two entries: first a quantity in column B, then a number somewhere else. Only the first should get a date.

Task In the stockroom, someone enters the delivered quantity in column B. Write the event procedure Worksheet_Change so that today's date (Date) then appears in column C of the same row. Entries outside column B should not trigger anything: check that with Intersect. The exercise types 12 into B3 and then 7 into E2.

ABCD
1ItemDeliveredLogged on
2Copy paper A4
3Black toner
4Lever arch file
5Blue ballpoint pens
6Sticky notes

How an event procedure is built

Private Sub Worksheet_Change(ByVal Target As Range)
    If Not Intersect(Target, Range("B:B")) Is Nothing Then
        Application.EnableEvents = False
        Target.Offset(0, 1).Value = Date
        Application.EnableEvents = True
    End If
End Sub
PartMeaning
Worksheet_ChangeThe name is fixed: object, underscore, event. That is how Excel recognises the procedure.
ByVal Target As RangeThe changed cell or range. Excel fills in the argument.
Intersect(Target, Range("B:B"))The overlap of both ranges. If Target is not in column B, the result is Nothing.
Application.EnableEvents = FalseExcel stops raising events for now, so your own change does not fire Worksheet_Change again.

Without Intersect the macro reacts to every change on the sheet. In the exercise above it then writes a date next to every cell, including next to the date it has just written, further and further to the right. In the end the exercise reports "Run-time error '28': Out of stack space".

Where the code goes in real Excel

Event macros do not live in a module like your other macros. They go in the code window of the sheet whose events they handle:

  1. Open the code window: right-click the sheet tab at the bottom of Excel and choose View Code. Or double-click the sheet in the VBA editor's Project Explorer, for example "Sheet1 (Stock)".
  2. Pick the event: at the top of the code window choose Worksheet on the left and Change on the right. The editor inserts the procedure frame with the correct header.
  3. Add your code and save as .xlsm. From now on the macro runs on every entry on this sheet, and not on other sheets.

Events for the whole workbook, such as opening it (Workbook_Open), go in ThisWorkbook. If Worksheet_Change ends up in a normal module by mistake, nothing happens on entry and there is no message. The exercises here have a single code window that stands for the sheet. If the procedure is missing or misspelled, the hint says: "This task needs the event procedure Worksheet_Change(ByVal Target As Range)."

Find the bug: endless loop

The classic event problem: the macro changes the very cell that triggered it. That change fires the event again, and so on.

Task Find the bug: item codes in column A should switch to capitals automatically after they are entered. But the event procedure crashes with "Run-time error '28': Out of stack space" as soon as someone types into column A (the exercise types tn-220 into A3). Switch events off with Application.EnableEvents = False before writing, and back on afterwards.

ABCD
1Item codeDescription
2AB-101Copy paper A4
3Black toner
4Lever arch file
5Sticky notes

This exercise is part of Premium.

Premium unlocks every exercise in every lesson, unlimited practice with fresh tasks and the final test with certificate.

See Premium Already Premium? Log in

The first exercise in this lesson is free.

In real Excel the macro keeps calling itself in the same way until VBA gives up. The exercise reports "Run-time error '28': Out of stack space", because every call takes up memory and that memory eventually runs out.

Other events

EventWhereWhen
Worksheet_ChangeWorksheetAfter cell contents change by typing, pasting, deleting or a macro. Not when only a formula's result changes.
Worksheet_SelectionChangeWorksheetWhen another cell is selected.
Worksheet_ActivateWorksheetWhen the sheet is activated.
Workbook_OpenThisWorkbookWhen the file opens, if macros are enabled.
Workbook_BeforeSaveThisWorkbookJust before saving.

The exercises here replay Worksheet_Change only. The others follow the same pattern in real Excel.

Common mistakes

EnableEvents stays off

If the macro stops with an error between EnableEvents = False and = True, events stay switched off. No event macro reacts any more until you type Application.EnableEvents = True in the Immediate window or restart Excel. The safe way is error handling that always reaches the line that switches them back on.

Several cells at once

When someone pastes a block or clears several cells, Target is a range of many cells. Target.Value is then an array, and a comparison like Target.Value > 10 fails with a run-time error. Check with If Target.Count > 1 Then Exit Sub, or loop over the cells with For Each.

Undo is gone

Once an event macro writes to the sheet, Ctrl+Z can no longer undo the entry before it. That is true for every macro; with events you just notice it more, because they run on every entry.

FAQ

Why does my event macro not run?

Three common reasons: the code is in a module instead of the sheet's code window, the name is misspelled, or EnableEvents is still False. Also check whether macros are enabled for the file at all; see Enable macros.

Why ByVal Target?

That is the header Excel inserts when you add the event through the drop-downs. Keep it exactly like that. If the header does not match the event, with a different type for Target for example, the VBA editor reports a compile error.

How do I test an event macro?

Put a breakpoint on its first line and type something into the sheet. Excel pauses, and you carry on with F8 like with any other macro.

Up next: customer report project

To finish level 5 you combine arrays, the Dictionary and error handling into a report like the one a sales team needs every month.

Customer report project

Write to us

Choose language

Select your preferred language