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.

ABCDE
1ItemPriceSearchPrice
2P-1004.85P-999
3P-14064.90
4P-2152.40
5P-2300.65
6P-3101.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

StatementWhat happens on an errorUse it for
On Error Resume NextThe 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 labelVBA jumps to the line label: and continues there.One error section for the whole macro: report, tidy up, stop.
On Error GoTo 0Back 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.

ABCD
1ItemAmountQtyUnit price
2Copy paper A497.0020
3Black toner194.703
4Lever arch file60.0025
5Blue ballpoint pens32.50
6Sticky notes23.4012

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

ABCD
1Sheet:April
2
3
4
5

January

ABCD
1Report January
2
3
4
5

February

ABCD
1Report February
2
3
4
5

March

ABCD
1Report 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.

Learn this next: procedures with arguments

Big macros become readable once you split them into small parts. You learn Sub and Function with arguments, ByVal and ByRef, optional arguments and calling with or without Call.

Procedures with arguments

Write to us

Choose language

Select your preferred language