Tabellab

Worksheet Events

Lesson 1 of 8Reading

Code that runs itself

Everything so far has waited for a button. An event is different: Excel calls your code automatically when something happens. The most useful of them is Worksheet_Change, which fires every time a cell on that sheet is edited. It is how a line total appears the instant somebody types a quantity, and how you get an audit stamp nobody has to remember to write.

Step one: build the sheet

Put this in a normal module (Insert → Module) and run it. It creates an Orders sheet with the six columns the event code expects, so you can try the whole thing in a blank workbook:

Option Explicit

Sub SetUpOrdersSheet()
    Dim ws As Worksheet
    Dim found As Worksheet

    For Each ws In ThisWorkbook.Worksheets
        If ws.Name = "Orders" Then Set found = ws
    Next ws

    If found Is Nothing Then
        Set found = ThisWorkbook.Worksheets.Add
        found.Name = "Orders"
    End If

    found.Cells.Clear
    found.Range("A1:F1").Value = Array("Date", "Item", "Qty", _
                                       "Unit price", "Total", "Last edited")
    found.Range("A1:F1").Font.Bold = True
    found.Range("A2").Value = Date
    found.Range("B2").Value = "Sample item"
    found.Columns("A:F").ColumnWidth = 15
    found.Activate
    found.Range("C2").Select

    MsgBox "Sheet 'Orders' is ready. Now paste the event code into " & _
           "the module of THIS sheet, then type a quantity in C2 " & _
           "and a price in D2.", vbInformation
End Sub

Step two: the event has to live in the sheet

Sheet events only work in that sheet's own module. In the Project Explorer on the left, double-click Sheet… (Orders) — not the module you just used. An empty code window opens; paste the block below into it. Nothing is run by hand from now on: type a quantity in C2 and a price in D2 and watch columns E and F fill themselves.

Option Explicit

Private Sub Worksheet_Change(ByVal Target As Range)
    Dim watched As Range
    Dim cell As Range
    Dim qty As Variant
    Dim price As Variant

    Set watched = Intersect(Target, Me.Range("C2:D10000"))
    If watched Is Nothing Then Exit Sub

    On Error GoTo CleanUp
    Application.EnableEvents = False

    For Each cell In watched
        qty = Me.Cells(cell.Row, "C").Value
        price = Me.Cells(cell.Row, "D").Value

        If Len(qty) > 0 And Len(price) > 0 _
           And IsNumeric(qty) And IsNumeric(price) Then
            Me.Cells(cell.Row, "E").Value = qty * price
            Me.Cells(cell.Row, "F").Value = Now
            Me.Cells(cell.Row, "F").NumberFormat = "dd mmm yyyy hh:mm"
        Else
            Me.Cells(cell.Row, "E").Resize(1, 2).ClearContents
        End If
    Next cell

CleanUp:
    Application.EnableEvents = True
End Sub

Line by line

  • Target is the range that changed. It is not always one cell — a paste, a fill handle or a delete hands you hundreds at once, which is why the code never touches Target.Value directly.
  • Intersect(Target, Me.Range("C2:D10000")) asks what the edit and the columns you care about have in common, and returns Nothing if there is no overlap. The Exit Sub after it is the most important line here: the event fires on every edit anywhere on the sheet, so the first job is to leave again.
  • Me is the sheet the code lives in, so the macro cannot write to whatever sheet happens to be active.
  • Len(qty) > 0 comes before IsNumeric(qty) on purpose: an empty cell returns Empty, and IsNumeric(Empty) is True. Without the length test, clearing a cell would write a zero.
  • The Else branch clears E and F, so deleting a quantity removes the stale total instead of leaving a wrong one.
  • On Error GoTo CleanUp with the CleanUp: label means every ending, success or failure, passes through the line that switches events back on.

The trap: the workbook that stops reacting

If your event code writes to the sheet, that write is itself a change, which fires the event again, which writes again, until Excel gives up with an out-of-stack error. Application.EnableEvents = False prevents that — and then becomes the trap. Unlike ScreenUpdating, Excel never switches events back on by itself, and the setting belongs to the whole application, not to one workbook. A macro that fails before restoring it leaves every event in every open workbook dead until you quit Excel. Hence the CleanUp label, and this rescue macro in your personal workbook:

Sub EventsOn()
    Application.EnableEvents = True
    Application.ScreenUpdating = True
    Application.Calculation = xlCalculationAutomatic
End Sub

The other sheet events

Worksheet_SelectionChange fires when the cursor moves — useful for highlighting the active row, but it runs constantly, so keep it tiny. Worksheet_BeforeDoubleClick and Worksheet_BeforeRightClick both hand you a Cancel argument: set it to True and Excel's normal behaviour is suppressed, which turns a double-click on a row into open this record in a form.

Event code does not stop at a breakpoint the way a normal macro does — you are inside Excel's own call. To see what Target contained, add Debug.Print Target.Address and read the Immediate window afterwards.

How it goes on

This lesson automates one sheet. The next moves up a level to workbook events, such as running something on open or refusing to save while a field is empty. From there the course leaves single files behind: looping through a folder with Dir, consolidating many workbooks into one dataset, building the report sheet itself, exporting it to PDF, sending it through Outlook, and finally making the whole chain fast enough to run unattended.

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_Change with the parameter ByVal 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. Target is 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: DateB: ItemC: QtyD: Unit priceE: TotalF: Last edited
Row 226 Oct 2026A4 paper (box)423.5094.0026 Oct 2026 09:12
Row 326 Oct 2026Toner cartridge268.90137.8026 Oct 2026 09:14
Row 427 Oct 2026Desk lamp145.0045.0027 Oct 2026 14:03
Row 527 Oct 2026Whiteboard markers121.8522.2027 Oct 2026 14:05
Row 628 Oct 2026Office 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

What Intersect(Target, watched range) returnsABCDEF123456789C4:D6… to row 10000Watched range C2:D10000only these edits matterTyping in B2Intersect = Nothing → Exit SubPaste over B4:D6 (Target)9 cells arrive in one eventIntersect result C4:D6loop visits these 6 cells
Typing in B2 has no overlap with the watched columns, so the handler leaves on its second line. A paste over B4:D6 arrives as one event with nine cells, and the loop only visits the six that fall in columns C and D.

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 doesTarget.AddressCells in TargetCells after Intersect
Types a quantity in C2$C$211
Types an item name in B2$B$210 (Nothing, exit)
Pastes a 3 × 3 block onto B4$B$4:$D$696 (C4:D6)
Fills a price down from D2 to D500$D$2:$D$500499499
Selects column C and presses Delete$C:$C1,048,5769,999 (C2:C10000)

Step by step: building it in Excel

  1. Open a new workbook and save it straight away as Excel Macro-Enabled Workbook (*.xlsm) with F12. A normal .xlsx throws event code away on save.
  2. Press Alt+F11, choose Insert → Module, paste the SetUpOrdersSheet macro from the lesson and run it with F5. It creates the Orders sheet with the six headers.
  3. 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.
  4. Paste the Worksheet_Change handler from the lesson into that window. Choose Debug → Compile VBAProject to catch typos before the first edit.
  5. Return to the sheet with Alt+F11 again (it toggles), type 4 in C2 and 23.50 in D2. Columns E and F should fill instantly.
  6. 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.
  7. Put the EventsOn rescue 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.

Why the handler switches events off while it writesWithout the guardUser types C2one changeWorksheet_ChangerunsWrites E2another changeHandler runs again…until "Out of stack space"repeatsWith the guard (the lesson's code)User types C2one changeIntersect?else Exit SubEnableEvents= FalseWrite E2, F2no new eventCleanUp:EnableEvents = Trueon any error: On Error GoTo CleanUp jumps straight here
Top: an unguarded handler triggers itself. Bottom: the lesson's pattern switches events off only while it writes, and the CleanUp label guarantees they come back on, whether the loop finished or failed.

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.

Event code is hard to step through, because it starts when you edit a cell rather than when you press F5. Add a temporary 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 Intersect test 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:D10000 is 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. ActiveSheet or a bare Cells can point somewhere else when code in another workbook triggers the change.
  • Keep messages out. A MsgBox inside Worksheet_Change interrupts 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.

Illustration of an automated Excel reporting workflow, from worksheet events to a finished report
Worksheet events are the first link in the automation chain this course builds, ending with a report that leaves by email.

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.EnableEvents in 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.Value as 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. IsNumeric of an empty cell is True. Test Len(qty) > 0 first.
  • The handler runs slowly after a big delete. It loops over Target rather 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

ItemWhat it does
Right-click sheet tab → View CodeOpens that sheet's own module, where sheet events must live
Alt+F11, Ctrl+RVBA 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 = FalseStops your own writes from raising new events (application-wide)
On Error GoTo CleanUpSends 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+GLogs what changed to the Immediate window
Worksheet_SelectionChangeRuns whenever the selection moves
Worksheet_BeforeDoubleClick / BeforeRightClickRuns 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.UserName by 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 BeforeDoubleClick with Cancel = 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.

  1. Workbook Events
  2. Looping Through Files with Dir
  3. Consolidating Many Workbooks
  4. Building a Report Sheet
  5. Exporting to PDF
  6. Sending the Report via Outlook
  7. Making It Fast

Buy course — €9.90 See the full course

Knowledge check

A Worksheet_Change handler fails halfway through, before it can restore Application.EnableEvents. What is the consequence?

Continues in this course
  • Workbook Events
  • Looping Through Files with Dir
  • Consolidating Many Workbooks
  • Building a Report Sheet
  • Exporting to PDF
  • Sending the Report via Outlook

Buy the course to unlock the remaining 7 lessons, the exam and the certificate.

Buy course — €9.90