Who this lesson is for
You already write macros that run when somebody clicks a button. That works, until the person who is supposed to click the button forgets. Totals are not refreshed, nobody records when a line was last changed, and the weekly report is built on numbers that are half a day out of date. This free lesson is for anyone who maintains an order list, a stock sheet, a project tracker or any shared workbook and wants Excel to do the routine part on its own, the moment the data changes.
The tool for that is an event: a procedure that Excel calls automatically when something happens. The most useful of all is Worksheet_Change, and it is the first step of the whole automation chain this course builds, from a sheet that reacts to typing, to a report that is collected, formatted, exported and sent without anyone touching it.
The core idea: Excel calls you
In a normal macro, you are in charge: you press F5 or a button, and your code runs from top to bottom. With an event, Excel is in charge. You write a procedure with a fixed name in a fixed place, and Excel runs it whenever the matching thing happens. Three rules follow from that, and almost every event problem breaks one of them.
- The name is fixed. It must be exactly
Worksheet_Changewith the parameterByVal Target As Range. Choose the sheet in the left drop-down at the top of the code window and the event in the right one, and the editor writes the correct first line for you. - The place is fixed. Sheet events live in the module of that sheet, listed under Microsoft Excel Objects in the Project Explorer. The fastest way there is to right-click the sheet tab and choose View Code. The same procedure in a standard module is never called.
- You do not control how much changed.
Targetis the range that was edited. It is one cell when someone types, but a paste, a fill-down or a Delete on a whole column hands you thousands of cells in a single call.
The worked example: an order sheet that fills itself in
The lesson above builds an Orders sheet with six columns: Date, Item, Qty, Unit price, Total and Last edited. People type only the first four. As soon as both a quantity and a price are present, the event writes the line total into column E and a timestamp into column F. If either value is deleted, both calculated cells are cleared again. Here is what the sheet looks like after a few days of use, with example numbers:
| A: Date | B: Item | C: Qty | D: Unit price | E: Total | F: Last edited | |
|---|---|---|---|---|---|---|
| Row 2 | 26 Oct 2026 | A4 paper (box) | 4 | 23.50 | 94.00 | 26 Oct 2026 09:12 |
| Row 3 | 26 Oct 2026 | Toner cartridge | 2 | 68.90 | 137.80 | 26 Oct 2026 09:14 |
| Row 4 | 27 Oct 2026 | Desk lamp | 1 | 45.00 | 45.00 | 27 Oct 2026 14:03 |
| Row 5 | 27 Oct 2026 | Whiteboard markers | 12 | 1.85 | 22.20 | 27 Oct 2026 14:05 |
| Row 6 | 28 Oct 2026 | Office chair | (deleted) | 189.00 | (cleared) | (cleared) |
| Check | =SUM(C2:C6) → 19 | =SUM(E2:E6) → 299.00 | =COUNT(E2:E6) → 4 |
Row 6 shows the Else branch at work: someone deleted the quantity for the chair, so the stale total and timestamp were removed rather than left behind. The check formulas confirm the result. =SUM(E2:E6) returns 299.00, the sum of the four complete lines, and =COUNT(E2:E6) returns 4 because the cleared cell is empty, not zero. That distinction matters: if the code had written 0 instead of clearing, the count of completed lines would be wrong and any average built on it would be too low.
Could you get the total with a formula? Yes: =IF(AND(ISNUMBER(C2),ISNUMBER(D2)),C2*D2,"") in E2, filled down, does the same arithmetic. The timestamp is the part a plain formula cannot do. =NOW() is volatile, so it recalculates every time anything in the workbook recalculates; every row would show the current time, not the time it was edited. Workarounds with deliberate circular references and iterative calculation exist, but they are fragile and easy to break by accident. An event writes the time once, as a value, and it stays there.
Target, Intersect and the first line that matters
The event fires for every edit anywhere on the sheet, including edits in columns you do not care about. So the first job of the handler is to decide, as cheaply as possible, whether this edit concerns it at all. That is what Intersect does: it returns the overlap between two ranges, or Nothing if they do not overlap.
Set watched = Intersect(Target, Me.Range("C2:D10000"))
If watched Is Nothing Then Exit Sub
The table below shows how different the same event can look depending on what the user did. The last row is the reason the code never assumes Target is a single cell and never loops over Target itself: clearing a whole column would otherwise mean a million iterations.
| What the user does | Target.Address | Cells in Target | Cells after Intersect |
|---|---|---|---|
| Types a quantity in C2 | $C$2 | 1 | 1 |
| Types an item name in B2 | $B$2 | 1 | 0 (Nothing, exit) |
| Pastes a 3 × 3 block onto B4 | $B$4:$D$6 | 9 | 6 (C4:D6) |
| Fills a price down from D2 to D500 | $D$2:$D$500 | 499 | 499 |
| Selects column C and presses Delete | $C:$C | 1,048,576 | 9,999 (C2:C10000) |
Step by step: building it in Excel
- Open a new workbook and save it straight away as Excel Macro-Enabled Workbook (*.xlsm) with
F12. A normal.xlsxthrows event code away on save. - Press
Alt+F11, choose Insert → Module, paste theSetUpOrdersSheetmacro from the lesson and run it withF5. It creates the Orders sheet with the six headers. - Back in Excel, right-click the Orders tab and choose View Code. Check the title bar of the code window: it should name the sheet, not Module1.
- Paste the
Worksheet_Changehandler from the lesson into that window. Choose Debug → Compile VBAProject to catch typos before the first edit. - Return to the sheet with
Alt+F11again (it toggles), type 4 in C2 and 23.50 in D2. Columns E and F should fill instantly. - Test the edge cases on purpose: delete C2, paste a block of quantities over several rows, type text such as "four" into C3, and select column D and press Delete. Each one should leave the sheet in a sensible state.
- Put the
EventsOnrescue macro from the lesson into a standard module, or better into your Personal Macro Workbook, so it is there the day an error leaves events switched off.
The trap: a workbook that stops reacting
When your handler writes to the sheet, that write is itself a change. Without protection the event would call itself, write again, call itself again, and stop only when Excel runs out of stack space. Application.EnableEvents = False breaks that loop. But it is an application setting: it switches off events in every open workbook, and Excel never switches it back on by itself, not even when the macro ends. If your code fails between the two lines, every event everywhere stays dead until you restore it or restart Excel.
That is why the handler uses On Error GoTo CleanUp and a label just before End Sub. Every path through the procedure, success or failure, ends by passing through Application.EnableEvents = True. If you ever suspect events have died, open the Immediate window with Ctrl+G and type ?Application.EnableEvents. If it prints False, run the rescue macro.
Debug.Print Target.Address as the first line, make your edits, and read the list of addresses in the Immediate window afterwards.The other sheet events worth knowing
The same sheet module offers more events in its right-hand drop-down. Worksheet_SelectionChange runs every time the selection moves, which makes it handy for highlighting the current row but expensive if it does real work, so keep it tiny. Worksheet_Activate runs when the sheet is selected. Worksheet_BeforeDoubleClick and Worksheet_BeforeRightClick run before Excel acts and give you a Cancel argument. Set it to True and the normal action, such as entering edit mode, does not happen:
Private Sub Worksheet_BeforeDoubleClick(ByVal Target As Range, Cancel As Boolean)
If Intersect(Target, Me.Range("B2:B10000")) Is Nothing Then Exit Sub
Cancel = True
MsgBox "Order line " & Target.Row - 1 & ": " & Target.Value, vbInformation
End Sub
Double-click an item name and you get your own action instead of the cell editor; double-click anywhere else and Excel behaves normally. In a later course this is exactly how a row opens in a data-entry form.
Keeping event code fast and safe
An event handler runs far more often than a button macro, often hundreds of times in a working day, and every run happens while the user is waiting to type the next value. A few habits keep it invisible:
- Leave early. The
Intersecttest should be the first real line. Anything before it, such as reading settings or looking up other sheets, is paid on every edit in every column. - Watch a bounded range.
C2:D10000is deliberate. Watching whole columns works, but a column delete then hands the loop a million cells instead of ten thousand. - Write only what changed. The lesson's loop touches the row of each intersected cell, not the whole table, so a single edit costs two writes.
- Read through
Me.Me.Cells(cell.Row, "C")always means the sheet that owns the code.ActiveSheetor a bareCellscan point somewhere else when code in another workbook triggers the change. - Keep messages out. A
MsgBoxinsideWorksheet_Changeinterrupts every paste. Mark problems with a colour or a note in the row instead, and save dialogs for buttons.
Note that a paste of 3 × 3 cells over B4:D6 visits row 4 twice, once for C4 and once for D4. That is harmless here, because both visits compute the same total, but it is worth knowing when your handler does something that should happen only once per row, such as appending a line to a log.

Common mistakes and how to spot them
- Nothing happens at all. The code is in a standard module or in the wrong sheet's module, or events are switched off. Check the code window's title bar, then type
?Application.EnableEventsin the Immediate window. - Excel freezes or shows "Out of stack space". The handler writes to the sheet without switching events off first, so it keeps calling itself.
- Run-time error 13, "Type mismatch", after a paste. The code used
Target.Valueas if it were one value. With several cells it is an array. Loop over the intersected range instead, as the lesson does. - Clearing a quantity writes 0 instead of clearing the total.
IsNumericof an empty cell isTrue. TestLen(qty) > 0first. - The handler runs slowly after a big delete. It loops over
Targetrather than over the intersection, or the watched range is a whole column. Restrict the range to the rows you actually use. - Timestamps all change at once. Someone replaced the event with
=NOW()in column F, which recalculates. Event-written times are values and stay fixed. - Users can undo nothing. Any macro that changes the sheet clears Excel's undo list. That is normal VBA behaviour; tell users, and keep event code limited to the cells it must touch.
Quick reference
| Item | What it does |
|---|---|
| Right-click sheet tab → View Code | Opens that sheet's own module, where sheet events must live |
Alt+F11, Ctrl+R | VBA editor and Project Explorer |
Private Sub Worksheet_Change(ByVal Target As Range) | Runs after any cell on the sheet is edited, pasted or cleared |
Intersect(Target, Me.Range("C2:D10000")) | The part of the edit that falls in your columns, or Nothing |
Application.EnableEvents = False | Stops your own writes from raising new events (application-wide) |
On Error GoTo CleanUp | Sends every error to the line that restores events |
Now / NumberFormat = "dd mmm yyyy hh:mm" | Fixed timestamp written as a value, displayed with date and time |
Debug.Print Target.Address, Ctrl+G | Logs what changed to the Immediate window |
Worksheet_SelectionChange | Runs whenever the selection moves |
Worksheet_BeforeDoubleClick / BeforeRightClick | Runs first; Cancel = True suppresses Excel's default action |
=IF(AND(ISNUMBER(C2),ISNUMBER(D2)),C2*D2,"") | Formula equivalent of the total column |
Real-world uses
- Audit stamps. Record when, and with
Application.UserNameby whom, a status or amount was last changed, so questions about who edited a line have an answer. - Order and quote sheets. Line totals, discounts and VAT columns that appear as soon as quantity and price are present, without formulas that a user can overwrite.
- Status tracking. When a project status changes to "Done", write the completion date in the next column automatically and colour the row.
- Input clean-up. Trim spaces, convert item codes to upper case or reject impossible values the moment they are typed, instead of cleaning them up at month end.
- Quick lookups. A double-click on a customer name opens their history or filters another sheet, using
BeforeDoubleClickwithCancel = True.
What you will build in the rest of this course
This first lesson is free. The remaining seven lessons are part of the paid course and take you from one reacting sheet to a complete, unattended reporting chain.
Workbook Events. You move from one sheet to the whole file: code that prepares the workbook when it opens, refuses to save while a required field is empty, and reacts to changes on any sheet from one place in ThisWorkbook.
Looping Through Files with Dir. You use the built-in Dir function to list every matching file in a folder, so a macro can work through twelve monthly files as easily as one.
Consolidating Many Workbooks. You open each file, find exactly how much data it holds, copy it below what is already collected and close it again without saving, building one clean dataset from many.
Building a Report Sheet. You rebuild the report from scratch every run, with headings, totals and formatting, so it can never drift out of step with the data or keep a stale row.
Exporting to PDF. You turn a sheet or a workbook into a properly named PDF with ExportAsFixedFormat, with no printer driver and no add-in.
Sending the Report via Outlook. You drive Outlook from Excel to create an email, attach the PDF and either show it for checking or send it directly, and you learn when to choose early or late binding.
Making It Fast. You remove the slow parts of the chain, mostly by touching the worksheet less often, so the whole process runs quickly enough to be left alone.
Summary
A Worksheet_Change handler lives in the sheet's own module and runs after every edit. Leave immediately with Intersect when the edit is not yours, loop over the intersection rather than over Target, switch events off while you write, and route every exit through a CleanUp label that switches them back on. Verify the result with =SUM and =COUNT on the calculated column. If you have not tried it yet, scroll up, build the Orders sheet, and then try to break it with a paste and a column delete. Then answer the quiz question about the one setting Excel never restores for you.
Frequently asked questions
What is the Worksheet_Change event in Excel VBA?
It is an event procedure that Excel runs automatically after any cell on a specific worksheet is changed by the user or by code. Its Target argument tells you which range changed.
Where do I put Worksheet_Change code?
In the code module of the sheet you want to watch. Right-click the sheet tab and choose View Code, then paste it there. Code in a standard module is never called by the event.
Why does my Worksheet_Change event not fire?
Usually the code is in the wrong module, the procedure name or argument list is wrong, or Application.EnableEvents was left at False by an earlier error. Check with ?Application.EnableEvents in the Immediate window.
How do I run a macro only when a specific cell or column changes?
Use Intersect(Target, Me.Range("C2:D10000")) and exit when the result is Nothing. Only edits that overlap that range get past the first two lines.
How can I add a timestamp when a cell is changed in Excel?
Write Now into the timestamp cell from a Worksheet_Change handler and give it a date-time number format. Because it is written as a value, it does not change on recalculation the way =NOW() does.
Why does Excel crash with Out of stack space in my event code?
Your handler changes the sheet, which fires the event again, endlessly. Set Application.EnableEvents = False before writing and make sure an error handler sets it back to True.
Keep going: Automation & Reports
This free lab is lesson 1 of 8. Unlock the other 7 hands-on labs, the final exam and your certificate for a one-time €9.90.
- Workbook Events
- Looping Through Files with Dir
- Consolidating Many Workbooks
- Building a Report Sheet
- Exporting to PDF
- Sending the Report via Outlook
- Making It Fast