Skip to content

Find a macro's bugs and handle its errors

Debug and automate9 minPremium

Builds on Repeat steps for every row with For and For Each.

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.

RowABC
1ToolWindowsWhat it does
2Step IntoF8Runs the yellow line and pauses on the next one. The yellow line is always the one about to run.
3BreakpointF9, or a click in the marginPauses the macro when it reaches that line
4ValuesHover over a variable, or View > Locals WindowShows what each variable holds now
5Immediate windowCtrlGType ?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:

VBA
Sub CopyWeeklyOrders()
On Error GoTo Problem
Worksheets("Orders").Range("A1").CurrentRegion.Copy _
Worksheets("Summary").Range("A1")
Exit Sub
Problem:
MsgBox "The orders weren't copied: " & Err.Description
End Sub
If the Orders or Summary sheet is missing, shows a message that says so and stops.

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 Sub before the label. The macro runs on into the message, so it reports a problem every time.
  • On Error Resume Next at 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 GoTo a label, Exit Sub before it, and a message with Err.Description.

Practice

Premium

4 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.