Find a macro's bugs and handle its errors
Debug and automate9 minPremium
A planning analyst in Boise runs the macro that copies each week's orders to the summary sheet. This week it stops with "Run-time error '9': Subscript out of range" and a line in yellow: someone renamed the Orders sheet.
How it works
When VBA can't carry out a line, it stops with a run-time error, its number and a message. Select Debug, and the editor shows the line in yellow, with the macro paused on it.
| Row | A | B | C |
|---|---|---|---|
| 1 | Tool | Windows | What it does |
| 2 | Step Into | F8 | Runs the yellow line and pauses on the next one. The yellow line is always the one about to run. |
| 3 | Breakpoint | F9, or a click in the margin | Pauses the macro when it reaches that line |
| 4 | Values | Hover over a variable, or View > Locals Window | Shows what each variable holds now |
| 5 | Immediate window | CtrlG | Type ?lastRow and press Enter to see a value |
F5 runs on from where the macro is paused, and Run > Reset stops it. On a Mac, use the editor's Debug, Run and View menus.
Some errors come from outside the code: a sheet renamed, a file moved. For those, catch the error and say what happened in plain words:
Sub CopyWeeklyOrders() On Error GoTo ProblemWorksheets("Orders"). Range( "A1"). CurrentRegion. Copy _ Worksheets("Summary"). Range( "A1") Exit SubProblem:MsgBox "The orders weren't copied: " & Err.Description End Sub
On Error GoTo Problem sends VBA to the line labeled Problem: when an error happens, and Err.Description is the error's message. Exit Sub ends the macro before the label when all goes well. The space and underscore at the end of a line continue it on the next one.
Common mistakes
- Reading the yellow line as one that has run. It's the next line to run.
- No
Exit Subbefore the label. The macro runs on into the message, so it reports a problem every time. On Error Resume Nextat the top of a macro. VBA skips every error without a word, and the macro carries on with wrong results.
In short
- Select Debug on an error to see the line, then step with F8 and pause with breakpoints.
- Hover, the Locals window or the Immediate window show what each value is.
On Error GoToa label,Exit Subbefore it, and a message withErr.Description.
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