VBA course · Lesson 19 of 33

Error handling and debugging in VBA

Handle run-time errors with On Error, Err and Resume, clean up safely, and debug with F8 stepping, breakpoints, the Immediate window, Locals and Watches.

Intermediate 20 min read

Every macro eventually meets a situation its author did not expect: a sheet was renamed, a file is missing, a cell contains text instead of a number. Without preparation, VBA stops with a grey error box, the user clicks End or, worse, Debug and lands in your code. This lesson covers both halves of dealing with problems: error handling (code that reacts sensibly when something goes wrong) and debugging (tools for finding out why your code does something you did not intend).

Three kinds of errors

KindWhen you notice itExample
Compile or syntax errorBefore or as the macro starts; the line turns red or a box says "Compile error"If x > 5 without Then, an undeclared variable with Option Explicit
Run-time errorWhile the macro runs; a box with a number and a messageError 9 "Subscript out of range" for a sheet that does not exist
Logic errorNever, unless you check the resultsA loop that starts at row 1 and treats the header as data

Compile errors are the friendliest: the editor points at the line. Choose Debug > Compile VBAProject regularly to catch them all at once, not only in the procedure you are running. Run-time errors are what On Error handles. Logic errors need debugging tools and careful testing, because VBA thinks everything is fine.

Common run-time errors you will meet:

NumberMessageTypical cause
6OverflowA value too big for the type, e.g. 40000 in an Integer
9Subscript out of rangeSheet or workbook name does not exist; array index outside the bounds
11Division by zeroDividing by an empty or zero cell
13Type mismatchText where a number was expected, or an error value in a Double
91Object variable or With block variable not setUsing an object variable before Set, often after Find found nothing
424Object requiredMissing Set, or a misspelled object name
1004Application-defined or object-defined errorMany Excel problems: bad range address, protected sheet, failed WorksheetFunction

On Error GoTo: the standard pattern

On Error GoTo label tells VBA: if a run-time error happens from here on, do not show the box, jump to this label instead. A label is a name followed by a colon at the start of a line. Here is the pattern you should use in most macros that users run:

VBA
Option Explicit

Sub ImportRates()
    Dim ws As Worksheet
    Dim rate As Double

    On Error GoTo ErrHandler

    Set ws = ThisWorkbook.Worksheets("Rates")      ' error 9 if the sheet is missing
    rate = ws.Range("B2").Value                      ' error 13 if B2 holds text
    ThisWorkbook.Worksheets("Invoices").Range("H1").Value = rate
    MsgBox "VAT rate " & Format(rate, "0%") & " copied."

    Exit Sub                                          ' normal end: skip the handler

ErrHandler:
    MsgBox "Could not import the rate." & vbCrLf & _
        "Error " & Err.Number & ": " & Err.Description, vbExclamation
End Sub
The standard error-handling pattern

Read the structure carefully:

  1. On Error GoTo ErrHandler switches the handler on.
  2. The normal work follows.
  3. Exit Sub ends the macro when everything went well. Without it, the code would fall through into the handler and show an error message even after success. Forgetting Exit Sub is the number-one mistake with this pattern.
  4. The handler, after the label, reports the problem. Err.Number and Err.Description describe the error that occurred.

The Err object

Err is always available and holds information about the most recent error:

  • Err.Number: 0 when there is no error, otherwise the error number.
  • Err.Description: the message text.
  • Err.Source: the name of the project or object that raised it.
  • Err.Clear: resets the object to "no error".
  • Err.Raise number, source, description: raises an error yourself.

Raising your own errors is useful in helper functions. When a function receives impossible input, it should not quietly return 0; it should raise an error that the caller can handle. Custom error numbers are conventionally built as vbObjectError + n:

VBA
Option Explicit

Private Const ERR_BAD_QTY As Long = vbObjectError + 1001

Function LineTotal(ByVal qty As Double, ByVal unitPrice As Double) As Double
    If qty <= 0 Then
        Err.Raise ERR_BAD_QTY, "LineTotal", "Quantity must be greater than zero."
    End If
    LineTotal = qty * unitPrice
End Function

Sub TestLineTotal()
    On Error GoTo ErrHandler
    Debug.Print LineTotal(3, 19.9)    ' 59.7
    Debug.Print LineTotal(0, 19.9)    ' raises the custom error
    Exit Sub
ErrHandler:
    If Err.Number = ERR_BAD_QTY Then
        MsgBox Err.Description, vbExclamation
    Else
        MsgBox "Unexpected error " & Err.Number & ": " & Err.Description
    End If
End Sub
Raising your own error and handling it in the caller

An error raised in a procedure without its own handler travels up to the caller. If the caller has an active handler, it catches it there. If no procedure in the chain has one, the user sees the standard error box.

Resume, Resume Next and On Error GoTo 0

After jumping into a handler, you have several ways to continue:

StatementEffect
ResumeRun the line that failed again (after you fixed the cause in the handler)
Resume NextContinue with the line after the one that failed
Resume labelContinue at another label, typically a clean-up section
On Error GoTo 0Switch error handling off again: errors stop the macro normally
On Error Resume NextIgnore errors from here on and continue with the next line

On Error Resume Next deserves special care. It is perfect for a single line where an error is expected and harmless, for example testing whether a sheet exists. It is dangerous as a blanket statement at the top of a macro, because then every error is silently ignored and your macro carries on producing nonsense. Always turn it off again with On Error GoTo 0 right after the risky line.

VBA
Option Explicit

Function SheetExists(ByVal sheetName As String, Optional ByVal wb As Workbook) As Boolean
    Dim ws As Worksheet
    If wb Is Nothing Then Set wb = ThisWorkbook
    On Error Resume Next
    Set ws = wb.Worksheets(sheetName)
    On Error GoTo 0
    SheetExists = Not ws Is Nothing
End Function

Sub CreateMonthSheet()
    Dim sheetName As String
    sheetName = Format(Date, "yyyy-mm")
    If SheetExists(sheetName) Then
        MsgBox "Sheet " & sheetName & " already exists."
    Else
        ThisWorkbook.Worksheets.Add(After:=ThisWorkbook.Worksheets(ThisWorkbook.Worksheets.Count)).Name = sheetName
    End If
End Sub
Safe use of On Error Resume Next for one test

If the sheet does not exist, the Set line fails, the error is ignored, and ws stays Nothing, so the function returns False.

Cleaning up, even when things go wrong

Many macros change application settings for speed (Make your macros fast: speed optimization in VBA) or open files. If an error stops the macro halfway, screen updating stays off and calculation stays manual, and the user thinks Excel is broken. Use a clean-up section that runs on both the normal and the error path:

VBA
Option Explicit

Sub BuildMonthlyReport()
    Dim wb As Workbook

    On Error GoTo ErrHandler
    Application.ScreenUpdating = False
    Application.Calculation = xlCalculationManual

    Set wb = Workbooks.Open(ThisWorkbook.Path & Application.PathSeparator & "sales_export.xlsx")
    ' ... copy data, build the report ...
    wb.Close SaveChanges:=False
    Set wb = Nothing

CleanUp:
    Application.Calculation = xlCalculationAutomatic
    Application.ScreenUpdating = True
    Exit Sub

ErrHandler:
    MsgBox "The report could not be built: " & Err.Description, vbCritical
    If Not wb Is Nothing Then wb.Close SaveChanges:=False
    Resume CleanUp
End Sub
A clean-up section that always runs

On success the code runs straight into CleanUp and exits. On an error it jumps to ErrHandler, closes the file if it was opened, and Resume CleanUp both clears the error state and jumps to the clean-up lines. Using Resume (rather than GoTo) matters: until a Resume runs, VBA considers you still "inside" the error, and a second error in the handler would not be caught. Application.PathSeparator gives \ on Windows and / on Mac.

Debugging: finding out what really happens

Error handlers deal with problems you foresaw. For everything else you need the debugging tools of the VBA editor. They are all in the Debug menu and on the Debug toolbar (View > Toolbars > Debug).

Stepping through code with F8

Click anywhere inside a macro and press F8 (Mac: Cmd+Shift+I, or use Debug > Step Into). The first line turns yellow: it is about to run. Each further F8 runs one line. Arrange the VBA window and the Excel window side by side and you can watch every change appear on the sheet. Hover the mouse over a variable to see its current value in a tooltip.

Related commands: Shift+F8 steps over a call (runs the whole called procedure in one go), Ctrl+Shift+F8 steps out of the current procedure, and Ctrl+F8 runs to the line where the cursor is. F5 continues normally until the end or the next breakpoint.

Breakpoints with F9

Stepping through 200 lines to reach the interesting one is tedious. Click in the grey margin left of a line, or press F9 on it, to set a breakpoint (a red dot). Run the macro with F5 and it pauses just before that line. Breakpoints are not saved with the file. A Stop statement in the code has the same effect and is saved, but remember to remove it before giving the file to others.

Tip. When an error box appears, click Debug instead of End. VBA highlights the failing line in yellow with all variables still alive, so you can inspect them. You can even fix the line, drag the yellow arrow back and press F5 to continue.

The Immediate window and Debug.Print

Press Ctrl+G (Mac: Cmd+Ctrl+G, or View > Immediate Window) to open the Immediate window. It has two uses:

  • Output: Debug.Print writes to it without interrupting the user. Use it to trace what a loop is doing.
  • Input: type ? followed by an expression and press Enter to evaluate it, for example ?ActiveSheet.Name, ?Range("E2").Value * 1.24 or ?ws.UsedRange.Address while paused. You can also run a single statement, e.g. Application.EnableEvents = True.
VBA
Option Explicit

Sub CheckInvoiceTotals()
    Dim ws As Worksheet
    Dim r As Long
    Dim lineSum As Double

    Set ws = ThisWorkbook.Worksheets("Invoices")
    For r = 2 To ws.Cells(ws.Rows.Count, "A").End(xlUp).Row
        lineSum = ws.Cells(r, "C").Value * ws.Cells(r, "D").Value
        Debug.Print r, ws.Cells(r, "A").Value, lineSum, ws.Cells(r, "E").Value

        ' Pause here if a stored total does not match quantity x price
        Debug.Assert Abs(lineSum - ws.Cells(r, "E").Value) < 0.005
    Next r
End Sub
Tracing a loop with Debug.Print and checking assumptions with Debug.Assert

Debug.Assert condition pauses the code (like a breakpoint) whenever the condition is False. It is a quick way to catch the first row that breaks an assumption. Debug.Print lines are invisible to users, but a failing Debug.Assert pauses their macro too and drops them into the editor, so remove assertions (and most Debug.Print lines) before you hand the file over.

The Locals window

View > Locals Window shows every variable of the current procedure with its value and type while the code is paused. For objects and arrays you can expand the tree, for example to look inside an array read from a range. It is the fastest way to answer "what is in this variable right now?".

Watches

A watch follows one expression. Select a variable or expression, choose Debug > Add Watch, and pick:

  • Watch Expression: just show the value in the Watches window.
  • Break When Value Is True: pause as soon as the expression becomes True, e.g. r = 1450 or total > 100000.
  • Break When Value Changes: pause whenever the value changes, perfect for finding which line sets a variable to a wrong value.

A debugging routine that works

  1. Reproduce the problem on a copy of the data.
  2. Read the error number and message, and click Debug to see the line.
  3. Inspect the variables on that line (hover, Locals, Immediate window).
  4. If the line itself is fine, the bad value came from earlier: set a breakpoint or a "Break when value changes" watch and run again.
  5. Fix the cause, not the symptom. Wrapping the line in On Error Resume Next is not a fix.
  6. Run Debug > Compile and test again with normal data, empty data and odd data (text in number columns, blank rows).
Note. On a Mac the debugging tools are the same, but some shortcuts differ or are missing depending on the keyboard; the Debug menu always works. The Locals and Watches windows are under the View menu as on Windows.

Common mistakes

  • Forgetting Exit Sub before the handler, so the error message appears after every successful run.
  • On Error Resume Next at the top of a long macro, hiding every bug.
  • Not resetting application settings in the error path.
  • Using GoTo instead of Resume to leave a handler, so a second error is not caught.
  • Showing Err.Description after another statement has already reset Err (for example after On Error GoTo 0, which clears it). Copy the number and text into variables first if you need them later.
  • Leaving Stop statements in a file you send to colleagues.

Check yourself

1. Why must there be an Exit Sub before the error-handler label?

2. Which statement switches error handling off again so errors stop the macro as normal?

3. What does Err.Raise vbObjectError + 1001, "Pricing", "Bad discount" do?

4. Which key sets or removes a breakpoint on the current line?

5. You want the code to pause the moment the variable total goes above 100,000. What do you use?