Excel VBA On Error GoTo: How Error Handling Works

VBA & macros · Updated November 19, 2026

In Excel VBA, On Error GoTo LabelName sends execution to a named error-handling section when a run-time error occurs in that procedure; for example, use On Error GoTo HandleError. The handler can report the problem, perform cleanup, and exit safely, while statements such as Resume Next let you handle selected errors differently.

What On Error GoTo means

VBA normally stops a macro when it encounters an unhandled run-time error, such as trying to open a file that does not exist or referring to a worksheet by a name that is absent. An On Error statement tells VBA what error-handling behavior to use in the current procedure. With On Error GoTo HandleError, VBA continues running normally until an error occurs; then it transfers control to the HandleError: label in that same procedure.

The label is an ordinary VBA line label, ending with a colon. It does not need a special name, but its name must match the one in the On Error statement. The handler is not a separate procedure: it belongs to the same Sub or Function as the code it handles. A separate procedure can have its own error handler, but a label in one procedure cannot serve as another procedure’s handler.

Error handling is not a promise that the macro will succeed. It is a way to decide what the program should do when a run-time problem occurs: show a useful message, close resources, skip a known optional operation, or pass the error back to the caller.

Basic syntax and control flow

A typical procedure has three parts: enable the handler, run the main work, and place the handler after a normal exit point. That exit point matters. Without it, successful execution can fall through into the handler code even though no error occurred.

Sub ExampleProcedure()
    On Error GoTo HandleError

    ' Main work goes here.
    Debug.Print "Procedure completed"
    Exit Sub

HandleError:
    MsgBox "Error " & Err.Number & ": " & Err.Description, vbExclamation
End Sub

The Exit Sub keeps normal execution from reaching HandleError:. In a function, use Exit Function before the handler. If the procedure needs to return a value, set its return value before exiting. The handler label can be positioned elsewhere in the same procedure, but placing it near the end often makes the flow easier to read.

After VBA transfers to an error handler, that handler is considered active until the procedure resumes execution or exits. If another error occurs while the handler is active, that same handler cannot simply catch it again; the error may be passed back to the calling procedure. Keep cleanup code small and deliberate, and protect cleanup operations that could themselves fail.

A practical file-opening example

This example opens a workbook, performs a placeholder check, and closes the source without saving. If opening or later work fails, it stores the original error details, attempts a quiet cleanup, and displays a message. Change the sample path to a real file before running it.

Sub OpenSourceWorkbook()
    Dim sourcePath As String
    Dim wb As Workbook
    Dim errorNumber As Long
    Dim errorDescription As String

    On Error GoTo HandleError

    sourcePath = "C:\Data\Monthly.xlsx"
    Set wb = Workbooks.Open(Filename:=sourcePath)

    ' Replace this line with the required processing.
    Debug.Print wb.Name

    wb.Close SaveChanges:=False
    Set wb = Nothing
    Exit Sub

HandleError:
    ' Save the original error before cleanup can change Err.
    errorNumber = Err.Number
    errorDescription = Err.Description

    If Not wb Is Nothing Then
        On Error Resume Next
        wb.Close SaveChanges:=False
        On Error GoTo 0
    End If

    MsgBox "Could not complete the operation." & vbCrLf & _
           "Error " & CStr(errorNumber) & ": " & errorDescription, _
           vbExclamation, "VBA error"
End Sub

The local On Error Resume Next is limited to the cleanup close, because a close attempt may fail if the workbook is already closed or otherwise unavailable. The following On Error GoTo 0 turns off that temporary behavior. Capturing Err.Number and Err.Description first preserves the original failure details; later operations can alter the current Err information. Save a copy of the workbook before running any macro: VBA changes cannot be undone with Ctrl+Z.

Choosing between GoTo, Resume Next, and GoTo 0

These statements have different purposes, so choosing one depends on whether an error is exceptional or expected:

  • On Error GoTo HandleError routes an error to a named handler. It is usually the clearest choice for a procedure that needs a controlled failure message or cleanup.
  • On Error Resume Next tells VBA to continue at the statement after the one that caused an error. It can be useful around one operation whose failure is anticipated, but leaving it active over a long procedure can conceal serious problems.
  • On Error GoTo 0 disables the currently enabled error handler in the procedure. Use it when you want normal VBA error behavior again, including after a narrowly scoped Resume Next.
  • On Error GoTo -1 resets the current error condition in the procedure. It is an advanced control-flow tool, not a label and not a replacement for GoTo 0; most straightforward handlers do not need it.

For example, if checking for an optional file is a deliberately tolerated operation, you might temporarily use On Error Resume Next, check whether the operation succeeded, and immediately restore normal handling with On Error GoTo 0. Do not use Resume Next as a general “ignore errors” switch: VBA may skip a failed assignment and continue with an empty object or an incorrect result.

How Resume changes what happens next

Inside a handler, Resume and its variations determine where execution goes after handling an error. Resume retries the statement that caused the error. That is useful only if the handler has corrected the cause and retrying is intentional; otherwise, the same error can recur. Resume Next continues with the statement immediately after the one that failed. It is different from using On Error Resume Next before an error: the former is a handler instruction, while the latter changes how subsequent errors are handled.

Resume SomeLabel continues at a specified label in the same procedure. A common pattern is to direct both successful work and handled errors toward a cleanup section, but the handler must first decide whether continuing is safe. If the operation cannot sensibly continue, capture the error, clean up, and exit rather than pretending that the failed step succeeded. When an error should be reported to a caller, VBA also provides Err.Raise to raise an error rather than silently swallowing it.

Using Err to understand a failure

The built-in Err object provides information about the most recent run-time error. Its commonly useful properties are Number, a numeric error code; Description, a human-readable explanation; and Source, which can identify the object or procedure that raised it. Capture any details you need at the start of the handler, before attempting cleanup or other work.

VBA’s Err.Clear clears the current error information, but it does not turn off an enabled error handler. Conversely, On Error GoTo 0 disables the handler; it is not merely a way to clear the description. Keeping those distinctions straight helps avoid confusing an empty Err object with disabled error handling.

For errors your code intentionally detects, you can raise a descriptive error with Err.Raise, optionally using a custom number, source, and description. Use a custom error when it adds useful context, and make the message specific enough to identify the failed operation. Avoid showing a raw error number alone: a user or maintainer needs to know what the macro was attempting and what action might resolve the issue.

Common mistakes and debugging advice

  • Forgetting the exit before the handler: successful code can run into the handler label. Add Exit Sub or Exit Function before it.
  • Using the wrong label: the label name must match exactly and must be within the same procedure. A misspelled or missing label causes a compile error, not a run-time error that the handler can catch.
  • Leaving Resume Next enabled: subsequent failures may be silently skipped. Limit its scope, check the outcome, and restore handling with On Error GoTo 0.
  • Assuming every problem is catchable: this mechanism handles run-time errors, not VBA syntax or compile errors. Fix compile problems in the editor before expecting a macro handler to run.
  • Overwriting the useful error: save the original Err details before calling cleanup code or displaying a complex message.
  • Retrying without fixing the cause: Resume repeats the failing statement. Use it only when the code has addressed the condition that caused the failure.

To inspect code on Windows, open the Visual Basic Editor from Developer > Visual Basic, or press Alt+F11. On Mac, use Tools > Macro > Visual Basic Editor, or Option+F11 (the Fn key may also be needed depending on keyboard settings). The editor’s Debug menu can help with compile and step-through debugging. Excel for the web does not run VBA macros; use the desktop Excel app for VBA. Macro security settings can also prevent code from running, so enable macros only in workbooks and files you trust.

Frequently Asked Questions

Does On Error GoTo catch every Excel VBA error?
It handles run-time errors in the procedure where the statement is active. It does not catch syntax or compile errors, and an error raised while the handler is already active may need to be handled by the caller.

Can I use On Error GoTo 0 to jump to the top of a procedure?
No. On Error GoTo 0 disables the current procedure’s error handler. It does not move execution; use an explicit label or another appropriate control-flow statement to change where code continues.

What is the difference between On Error GoTo 0 and GoTo -1?
GoTo 0 disables the enabled handler in the current procedure. GoTo -1 resets the current error condition. They are not interchangeable, and typical beginner-level error handlers usually need GoTo 0 only when turning handling off.

Can one error handler serve several VBA procedures?
No. A handler label belongs to one procedure. Each procedure that needs its own handling should define it, or it can let the error return to a calling procedure that has an active handler.

Why does my macro still stop after On Error GoTo?
Check that the statement runs before the error, the label exists in the same procedure, and no error is occurring inside an already active handler. Also check whether the failure is a compile error, which an On Error statement cannot handle.

Related

Try it: the Column Letter to Number: aA is 27, XFD is 16,384. Converts both ways.

More in VBA & macros

Sources: Function behaviour and menu paths: Microsoft Support documentation for Excel. Method & sources

Spotted an error in this guide? Let us know.