VBA Error Handling and Debugging: On Error, Breakpoints and the Immediate Window

VBA Error Handling and Debugging: On Error, Breakpoints and the Immediate Window

📎 This article includes 1 downloadable practice file ↓

⏱ 4 min read

Every macro breaks sooner or later — a renamed sheet, a missing file, text where a number should be. The difference between fragile and dependable code isn’t avoiding errors; it’s finding them quickly and handling the expected ones gracefully. This lesson covers both.

In this article
  1. Reading an error
  2. Debugging tools
  3. On Error GoTo: handle errors properly
  4. Always restore settings
  5. On Error Resume Next — use with care
  6. Prevent errors before they happen
  7. Practice
  8. Continue learning

Reading an error

When a macro fails you get a box with a number and a message, plus End and Debug. Click Debug — the editor highlights the failing line in yellow. The most common ones:

Advertisement
Number Message Usual cause
6 Overflow Integer too small — use Long
9 Subscript out of range Sheet/workbook name wrong, or array index past its end
13 Type mismatch Text where a number or date was expected, or a cell with #N/A
91 Object variable not set Missing Set, or a Find that found nothing
424 Object required Typo in an object name
1004 Application-defined error Excel refused: bad range address, protected sheet, illegal sheet name

Debugging tools

  • F8 — run one line at a time. Hover over a variable to see its value.
  • F9 — toggle a breakpoint (red dot). F5 runs until it reaches one.
  • View › Locals Window — every variable and its current value, updated as you step.
  • View › Immediate Window (Ctrl+G) — type ?lastRow to print a value, or run one line like Range("A1").Select.
  • Debug.Print — write values to the Immediate window while the macro runs, without stopping it.
For r = 2 To lastRow
    Debug.Print r, ws.Cells(r, 1).Value, ws.Cells(r, 5).Value
Next r
💡 Drag the yellow arrow in the margin to re-run a line after fixing a variable in the Immediate window — handy when testing tricky logic.

On Error GoTo: handle errors properly

Sub ImportStatement()
    Dim wb As Workbook
    On Error GoTo Failed

    Set wb = Workbooks.Open(ThisWorkbook.Path & "\statement.xlsx", ReadOnly:=True)
    wb.Worksheets(1).UsedRange.Copy ThisWorkbook.Worksheets("Import").Range("A1")
    wb.Close False
    MsgBox "Imported."
    Exit Sub                       ' don't fall into the handler

Failed:
    MsgBox "Couldn't import: " & Err.Description & " (error " & Err.Number & ")", vbExclamation
    If Not wb Is Nothing Then wb.Close False
End Sub

The Exit Sub before the label is essential; without it, the handler runs every time, even when nothing went wrong.

Always restore settings

Sub SafeMacro()
    Application.ScreenUpdating = False
    Application.Calculation = xlCalculationManual
    On Error GoTo Cleanup
    ' ... work ...
Cleanup:
    Application.Calculation = xlCalculationAutomatic
    Application.ScreenUpdating = True
    If Err.Number <> 0 Then MsgBox "Stopped: " & Err.Description
End Sub

Without this, a crash leaves Excel in manual calculation and users think their formulas are broken.

On Error Resume Next — use with care

It tells VBA to ignore errors and continue. Useful for one line you expect might fail, dangerous for whole procedures:

On Error Resume Next
Set ws = ThisWorkbook.Worksheets("Archive")     ' may not exist
On Error GoTo 0                                  ' switch normal errors back on immediately
If ws Is Nothing Then Set ws = ThisWorkbook.Worksheets.Add: ws.Name = "Archive"
⚠️ Leaving On Error Resume Next active hides every bug below it — the macro “finishes” having silently done half the work. Always follow it with On Error GoTo 0 after the one risky line.

Prevent errors before they happen

  • Check inputs: If Not IsNumeric(x) Then ... Exit Sub
  • Check results: If found Is Nothing Then ... after .Find
  • Check files: If Dir(path) = "" Then ...
  • Option Explicit at the top of every module

Practice

The workbook contains six broken macros, one for each error in the table above. Fix them using F8, the Locals window and the Immediate window — answers are in a second module.

Next: string functions — cleaning and splitting text.

⚡ Interactive Practice Lab & Formula Tester:

Test formulas dynamically in our web formula laboratory or download the companion Excel workbook.

📎 Practice files for this article

  • 📗
    Practice workbook with all course macros (.xlsm)Open it, click Enable Content in the yellow bar, go to the Macros sheet and press any button. 60 sales rows included to test on.
    ⬇ XLSM · 29 KB

Free to use for learning. Files with macros (.bas) are plain text — import them with Alt+F11 → File → Import File, and always test on a copy.

✨ Ask AI about this article

Stuck on a step? Ask a question and the AI answers using this article.

Free · AI can be wrong

Leave a Reply

Your email address will not be published. Required fields are marked *