Excel VBA error handling: catch errors instead of crashing
A run-time error stops your macro halfway through and shows the dialog with End and Debug. With On Error you decide in advance what should happen instead: skip the line and check what went wrong, or jump to your own error section and report the problem in plain words.
In short: On Error Resume Next carries on with the next line after an error, then you check Err.Number <> 0. On Error GoTo ErrHandler jumps to the label ErrHandler: on an error, with Exit Sub right before it. Err.Description returns the error text, and On Error GoTo 0 switches normal handling back on.
What you need to know: worksheet functions from WorksheetFunction, sheets from working with worksheets and the Dictionary.
Try it right now
WorksheetFunction.VLookup stops with run-time error 1004 when the lookup value is missing. That is exactly what happens in the starting code: item P-999 does not exist. Catch the error and write a note into the cell instead.
Task The macro FindPrice looks up the item in D2 in the price list with WorksheetFunction.VLookup. If the item is missing, it stops with run-time error 1004. Catch the error with On Error Resume Next and then check Err.Number: on an error, E2 should say "not found", otherwise it gets the price. Switch error handling back on at the end with On Error GoTo 0.
| A | B | C | D | E | |
|---|---|---|---|---|---|
| 1 | Item | Price | Search | Price | |
| 2 | P-100 | 4.85 | P-999 | ||
| 3 | P-140 | 64.90 | |||
| 4 | P-215 | 2.40 | |||
| 5 | P-230 | 0.65 | |||
| 6 | P-310 | 1.95 |
Real Excel also raises number 1004 for VLookup, but with its own text about the worksheet function. The exercise shows the VBA editor's general text. For the Err.Number check, only the number matters.
The three forms of On Error
| Statement | What happens on an error | Use it for |
|---|---|---|
On Error Resume Next | The failing line is skipped and the macro carries on. Err.Number holds the error number. | Single lines where an error is an expected answer: sheet missing, lookup value missing. |
On Error GoTo label | VBA jumps to the line label: and continues there. | One error section for the whole macro: report, tidy up, stop. |
On Error GoTo 0 | Back to normal: errors show the dialog and stop the macro. | Right after the section where you deliberately ignore errors. |
The Err object remembers the last error. Err.Number is 0 as long as everything went fine, and Err.Description is the text you would see in the error dialog. Err.Clear resets both, which you need when you check several times inside a loop with Resume Next.
One error section for the whole macro
Sub UnitPrice()
Dim i As Long
On Error GoTo ErrHandler
For i = 2 To 6
Cells(i, 4).Value = Cells(i, 2).Value / Cells(i, 3).Value
Next i
Exit Sub ' normal end, skip the error section
ErrHandler:
MsgBox "Error in row " & i & ": " & Err.Description
End Sub
The label is a name followed by a colon, on a line of its own, and everything below it is the error section. Exit Sub before it is essential: without it, the macro finishes its work and walks straight into the error section, showing the message although nothing went wrong. Err.Description is empty then.
Task The macro UnitPrice divides the amount by the quantity in each row. If a quantity is missing, it stops with a run-time error. Add error handling with On Error GoTo ErrHandler: when an error occurs, the macro shows exactly the message "Error in row 5: Division by zero" (row number and Err.Description from the run). If everything works, no message appears.
| A | B | C | D | |
|---|---|---|---|---|
| 1 | Item | Amount | Qty | Unit price |
| 2 | Copy paper A4 | 97.00 | 20 | |
| 3 | Black toner | 194.70 | 3 | |
| 4 | Lever arch file | 60.00 | 25 | |
| 5 | Blue ballpoint pens | 32.50 | ||
| 6 | Sticky notes | 23.40 | 12 |
This exercise is part of Premium.
Premium unlocks every exercise in every lesson, unlimited practice with fresh tasks and the final test with certificate.
See Premium Already Premium? Log in
The first exercise in this lesson is free.
Does the sheet exist yet?
A classic case for Resume Next: the simplest way to find out whether a sheet exists is to reach for it. If that fails, the object variable stays Nothing. Right after, switch back with On Error GoTo 0 so every other error gets noticed again.
Task The macro GetSheet should get the sheet named in B1. If that sheet does not exist yet, it adds a new one after the last sheet and gives it that name. It then writes "Report " plus the name into A1 of the sheet (new or existing), so "Report April". Catch the error when getting the sheet with On Error Resume Next and switch back with On Error GoTo 0 right after.
Start
| A | B | C | D | |
|---|---|---|---|---|
| 1 | Sheet: | April | ||
| 2 | ||||
| 3 | ||||
| 4 | ||||
| 5 |
January
| A | B | C | D | |
|---|---|---|---|---|
| 1 | Report January | |||
| 2 | ||||
| 3 | ||||
| 4 | ||||
| 5 |
February
| A | B | C | D | |
|---|---|---|---|---|
| 1 | Report February | |||
| 2 | ||||
| 3 | ||||
| 4 | ||||
| 5 |
March
| A | B | C | D | |
|---|---|---|---|---|
| 1 | Report March | |||
| 2 | ||||
| 3 | ||||
| 4 | ||||
| 5 |
This exercise is part of Premium.
Premium unlocks every exercise in every lesson, unlimited practice with fresh tasks and the final test with certificate.
See Premium Already Premium? Log in
The first exercise in this lesson is free.
In real Excel
Without error handling, Excel shows a dialog with the number and text of a run-time error. Debug opens the VBA editor and highlights the line in yellow, End stops the macro. While you develop that is handy; for colleagues who only start the macro with a button, it is not. Every macro other people use should have error handling with a clear message.
If your error section never kicks in inside the real editor, look under Tools > Options > General, Error Trapping. With Break on All Errors selected, VBA stops on every error despite On Error. That can be useful for testing; for everyday work choose Break on Unhandled Errors.
Common mistakes
On Error Resume Next for the whole macro
If Resume Next sits at the top and is never switched off, the macro swallows every error. It seems to run fine, but values are missing or wrong and nobody can see why. Limit Resume Next to the one line that needs it and write On Error GoTo 0 right after.
Forgetting Exit Sub
Then the error message appears on every run, even when everything worked. That is why the unit price exercise requires Exit Sub: in the check with other data no quantity is missing, so no message may appear.
Not resetting Err.Number
If you check Err.Number inside a loop with Resume Next, an error from the first pass stays there until you call Err.Clear. Without Clear, every following line looks as if it failed too.
Not preventing the error in the first place
Not every error needs On Error. Check for an empty quantity first with If Cells(i, 3).Value = 0 Then, and for text amounts with IsNumeric. Without a check, the exercise reports "Run-time error '11': Division by zero" on the empty cell. Error handling is for the unexpected, not a replacement for an If.
FAQ
What does Resume do?
In the error section, Resume label continues the macro at another label, for example to tidy up after a message. Resume Next in the error section jumps to the line after the one that failed in real VBA. The exercises here do not support that form, and you do not need it for this course.
Can I raise an error myself?
Yes, with Err.Raise number. That is useful in your own procedures when they should hand an error back to the caller. Procedures with arguments are next.
Does On Error apply inside procedures I call?
If the called procedure has no error handling of its own, VBA passes the error back up to the caller, and the caller's error section runs. If it has its own, that one comes first.
How do I find out exactly where it breaks?
Leave the error handling out while you develop, or print the row in the error section as in the exercise above. Breakpoints and stepping from Debugging show you the values just before the error.