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.
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
| Kind | When you notice it | Example |
|---|---|---|
| Compile or syntax error | Before 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 error | While the macro runs; a box with a number and a message | Error 9 "Subscript out of range" for a sheet that does not exist |
| Logic error | Never, unless you check the results | A 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:
| Number | Message | Typical cause |
|---|---|---|
| 6 | Overflow | A value too big for the type, e.g. 40000 in an Integer |
| 9 | Subscript out of range | Sheet or workbook name does not exist; array index outside the bounds |
| 11 | Division by zero | Dividing by an empty or zero cell |
| 13 | Type mismatch | Text where a number was expected, or an error value in a Double |
| 91 | Object variable or With block variable not set | Using an object variable before Set, often after Find found nothing |
| 424 | Object required | Missing Set, or a misspelled object name |
| 1004 | Application-defined or object-defined error | Many 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:
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 SubRead the structure carefully:
On Error GoTo ErrHandlerswitches the handler on.- The normal work follows.
Exit Subends the macro when everything went well. Without it, the code would fall through into the handler and show an error message even after success. ForgettingExit Subis the number-one mistake with this pattern.- The handler, after the label, reports the problem.
Err.NumberandErr.Descriptiondescribe 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:
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 SubAn 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:
| Statement | Effect |
|---|---|
Resume | Run the line that failed again (after you fixed the cause in the handler) |
Resume Next | Continue with the line after the one that failed |
Resume label | Continue at another label, typically a clean-up section |
On Error GoTo 0 | Switch error handling off again: errors stop the macro normally |
On Error Resume Next | Ignore 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.
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 SubIf 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:
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 SubOn 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.
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.Printwrites 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.24or?ws.UsedRange.Addresswhile paused. You can also run a single statement, e.g.Application.EnableEvents = True.
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 SubDebug.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 = 1450ortotal > 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
- Reproduce the problem on a copy of the data.
- Read the error number and message, and click Debug to see the line.
- Inspect the variables on that line (hover, Locals, Immediate window).
- 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.
- Fix the cause, not the symptom. Wrapping the line in
On Error Resume Nextis not a fix. - Run Debug > Compile and test again with normal data, empty data and odd data (text in number columns, blank rows).
Common mistakes
- Forgetting
Exit Subbefore the handler, so the error message appears after every successful run. On Error Resume Nextat the top of a long macro, hiding every bug.- Not resetting application settings in the error path.
- Using
GoToinstead ofResumeto leave a handler, so a second error is not caught. - Showing
Err.Descriptionafter another statement has already resetErr(for example afterOn Error GoTo 0, which clears it). Copy the number and text into variables first if you need them later. - Leaving
Stopstatements in a file you send to colleagues.
Check yourself
1. Why must there be an Exit Sub before the error-handler label?
Labels do not stop execution; without Exit Sub, the code falls through into the handler.
2. Which statement switches error handling off again so errors stop the macro as normal?
On Error GoTo 0 disables the active handler in the current procedure.
3. What does Err.Raise vbObjectError + 1001, "Pricing", "Bad discount" do?
Err.Raise creates an error just like a built-in one, with your own number and text.
4. Which key sets or removes a breakpoint on the current line?
F9 toggles a breakpoint; F8 steps one line and F5 runs.
5. You want the code to pause the moment the variable total goes above 100,000. What do you use?
A conditional watch pauses execution as soon as its expression becomes True.