Excel VBA On Error Exit Sub: How Error Handling Works

VBA & macros · Updated November 19, 2026

In Excel VBA, On Error Exit Sub is not a valid error-handling statement. To stop a procedure after an error, route execution to an error-handler label with On Error GoTo Handler, show or record the error there, and use Exit Sub to leave the procedure; the same exit statement also keeps normal execution from falling into the handler.

What On Error and Exit Sub mean

On Error tells VBA what to do when a run-time error occurs in the procedure. It does not itself end the macro. Exit Sub ends the current Sub procedure immediately, whether it is called from ordinary code or from an error handler. It does not close Excel, stop every other macro, or automatically undo changes already made.

For a handler-based approach, the usual shape is:

  • On Error GoTo Handler activates a named error handler.
  • The procedure runs its ordinary statements.
  • Exit Sub ends the successful path before it reaches the handler label.
  • The handler reports or manages the error, then exits the procedure.

The label is a line label within the same procedure, written with a colon. It is not a separate Sub, and a handler label cannot be used to jump directly into another procedure. If the procedure reaches the label during normal execution because the success path lacks Exit Sub, VBA will run the handler code even though no error occurred.

A basic error handler that exits the Sub

This example assumes the workbook contains a worksheet named Sheet1. It tries to convert cell A1 to a number. If the sheet is missing, the cell contains unsuitable text, or another run-time error occurs, execution moves to the handler instead of stopping with VBA’s default error dialog.

Save a copy of the workbook before running a macro: VBA changes cannot be reversed with Ctrl+Z. In Microsoft 365 for Windows, open the Visual Basic Editor with Alt+F11 or use Developer > Visual Basic. In Excel for Mac, use Option+F11 (some keyboards also require Fn) or the Developer tab. Excel for the web cannot run VBA macros.

Public Sub ReadA1Safely()
    Dim amount As Double

    On Error GoTo HandleError

    amount = CDbl(ThisWorkbook.Worksheets("Sheet1").Range("A1").Value)
    MsgBox CStr(amount)
    Exit Sub

HandleError:
    MsgBox "Could not read Sheet1!A1 as a number. " & Err.Description, vbExclamation
    Exit Sub
End Sub

The first Exit Sub matters: it ensures that a successful conversion ends the procedure rather than continuing down to HandleError:. The second one makes the handler’s intent explicit. Because the handler is at the end of this short procedure, that second exit could be omitted without changing the immediate result, but including it makes the control flow easier to extend safely.

Use cleanup before exiting

Some procedures acquire resources or change application state before an error can happen. Examples include opening another workbook, disabling events, changing calculation settings, or creating a temporary file. In those cases, immediately exiting from the handler can leave work half-finished. A safer design captures the original error, attempts cleanup, and then exits.

This example opens a source workbook and closes it if an error occurs during processing. It uses Application.PathSeparator rather than assuming a particular slash character in the file path.

Public Sub OpenSourceSafely()
    Dim sourcePath As String
    Dim sourceBook As Workbook
    Dim savedErrorNumber As Long
    Dim savedErrorDescription As String

    On Error GoTo HandleError

    sourcePath = ThisWorkbook.Path & Application.PathSeparator & "Source.xlsx"
    Set sourceBook = Workbooks.Open(Filename:=sourcePath)

    ' Put the workbook-processing steps here.

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

HandleError:
    savedErrorNumber = Err.Number
    savedErrorDescription = Err.Description

    ' Ignore a secondary error if cleanup itself fails.
    On Error Resume Next
    If Not sourceBook Is Nothing Then sourceBook.Close SaveChanges:=False
    On Error GoTo 0

    MsgBox "Error " & CStr(savedErrorNumber) & ": " & savedErrorDescription, vbExclamation
    Exit Sub
End Sub

Capturing Err.Number and Err.Description first is important: a cleanup operation can generate another error and replace the information about the original failure. The short On Error Resume Next section is restricted to cleanup, where the code deliberately tolerates a failure. It is then switched off with On Error GoTo 0 so later statements do not silently ignore errors.

When to use Resume Next instead

On Error Resume Next tells VBA to continue with the next statement after a run-time error. It does not jump to a handler label, and it does not automatically stop the Sub. This can be useful for one operation that may legitimately fail, such as checking whether an optional object is available, but it is risky across a long block of code: an unsuccessful statement may be followed by code that assumes it worked.

Keep it narrow and inspect the error immediately. For example, a procedure can try to access a named worksheet, check whether the reference was obtained, and then restore normal error handling. This pattern is more controlled than ignoring every error throughout a macro. If the error is not an expected possibility, a named handler is usually clearer because it funnels failures to one place where they can be reported or cleaned up.

Also distinguish “ignore this error and continue” from “handle this error and stop.” The former is the purpose of On Error Resume Next; the latter is typically On Error GoTo Handler followed by a deliberate Exit Sub after reporting or cleanup.

Choosing the right exit pattern

Choose the pattern based on what the procedure should do after the failure, not simply on which syntax looks shortest:

  • Report and stop: Use a named handler, show a useful message, and end with Exit Sub. This suits a macro that cannot safely continue.
  • Clean up, report, and stop: Save the error details, make a controlled cleanup attempt, report the original problem, and exit. Use this when the macro has opened files or changed state.
  • Ignore one known, optional failure: Use On Error Resume Next around only the relevant statement or small block, check Err, and then restore handling.
  • Let the caller decide: A reusable procedure may clean up and then re-raise an error with Err.Raise, rather than displaying a message and ending the whole operation locally. This lets a calling procedure choose how to respond.

A Sub can only exit itself with Exit Sub. If a larger routine calls several Subs, ending one child Sub does not inherently end the caller. A function has a different exit statement, Exit Function, and a property procedure uses the matching property exit statement.

Common mistakes and misconceptions

  • Writing On Error Exit Sub: VBA does not recognize this as a valid combined command. Use an On Error form to choose error handling and a separate Exit Sub where the procedure should stop.
  • Leaving out the success-path exit: If ordinary execution can reach the handler label, it will run the handler code without an error. Put Exit Sub immediately before the label in a simple handler layout.
  • Assuming Exit Sub reverses changes: It does not roll back cell edits, restore settings, or close workbooks. Write explicit cleanup or recovery steps when needed.
  • Using Resume Next for an entire macro: Errors may be hidden while later statements operate on missing or invalid data. Restrict it to an expected operation and check the result.
  • Using a handler that causes another error: While a procedure’s error handler is active, a new error inside that handler cannot simply be handled by the same active handler. Keep the handler simple and protect optional cleanup deliberately.
  • Expecting Ctrl+Z to undo a macro: Excel’s undo stack is generally cleared by running VBA. Save a backup before testing code that edits or deletes workbook content.

Testing and diagnosing the handler

Test both paths: a normal run where the procedure succeeds and a controlled failure where it should reach the handler. For the sample above, try a valid number in Sheet1!A1, then try text that cannot be converted. A missing worksheet can also trigger the handler, but use a copy of the workbook when changing test conditions.

When debugging, the Visual Basic Editor can stop on an error, highlight the current line, and let you inspect variables. The VBE’s error-trapping option affects whether execution breaks at an error or follows the procedure’s handler; for ordinary macro debugging, check Tools > Options > General and the Error Trapping setting. A breakpoint or stepping through code can also show whether the successful path passes the handler label accidentally. Remove temporary test statements before using the macro on important data.

Make error messages actionable. Include what the macro was attempting, the relevant file or sheet when appropriate, and the error number or description. Avoid reporting a vague “Something went wrong” if the user needs to correct a file path or input value. At the same time, do not claim that a procedure completed successfully if it exited after a failure.

Frequently Asked Questions

Can I write On Error Exit Sub in VBA?
No. It is not valid VBA syntax. Use On Error GoTo Label or another supported On Error form, and write Exit Sub as a separate statement.

Do I need Exit Sub after an error message?
Use it when execution could otherwise continue into ordinary code or another label. If the handler is the final code in a procedure, falling off the end also ends the Sub, but an explicit exit communicates intent and makes later edits less error-prone.

Does Exit Sub stop the whole macro?
It stops only the current Sub. If another Sub called it, the caller can continue after the call unless that caller also handles the failure or receives a raised error.

What is the difference between On Error GoTo 0 and Exit Sub?
On Error GoTo 0 disables the current procedure’s enabled error handler; it does not end the procedure. Exit Sub ends the current Sub. They address different parts of control flow.

Can I use Exit Sub inside an error handler?
Yes. It is a normal way to end the procedure after reporting or cleaning up. If the procedure must notify its caller instead of swallowing the failure, consider raising the error again rather than simply exiting.

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.