In Excel VBA, Exit Sub immediately ends the currently running Sub procedure and returns control to the code that called it, or to Excel if nothing called it. Use it when a procedure has finished its job or a condition means it should stop; it does not close Excel, stop every macro, or return a value.
What Exit Sub Does
A Sub procedure is a named block of VBA code that performs actions but does not return a value as a Function does. When VBA reaches Exit Sub, it skips the remaining statements in that particular procedure and resumes at the caller’s next statement. If the Sub was started directly from Excel, execution simply ends there.
The statement is an explicit exit point. It can appear in the middle of a procedure, commonly after a check that determines there is no useful work to do. It is not necessary to add it at the end of every Sub: reaching End Sub already ends the procedure normally. Adding an extra Exit Sub immediately before End Sub generally changes nothing.
Before running any macro that changes a workbook, save a separate copy first. VBA macros cannot be undone with Ctrl+Z, including changes made before an Exit Sub is reached.
A Basic Example
This example checks a worksheet range before formatting it. If the range is empty, the message appears and the procedure stops; the formatting statement is skipped. If there is data, VBA continues past the condition and formats the range.
Public Sub FormatReport()
Dim reportSheet As Worksheet
' Use the Report sheet in this workbook.
Set reportSheet = ThisWorkbook.Worksheets("Report")
If Application.WorksheetFunction.CountA(reportSheet.Range("A1:D20")) = 0 Then
MsgBox "There is no report data to format."
Exit Sub
End If
reportSheet.Range("A1:D20").Columns.AutoFit
End Sub
Here, CountA counts non-empty cells in the specified range. If the count is zero, Exit Sub prevents the later formatting line from running. The procedure ends; it does not skip only the If block and then carry on. That distinction is important when deciding where to place an exit.
Using Exit Sub for Validation and Guard Clauses
A common pattern is to check prerequisites near the start of a procedure and exit when they are not met. These early checks are sometimes called guard clauses. They keep the main work less deeply nested and make it clear why a macro did not continue.
For example, a macro that relies on the active selection can stop when the selection is not a range or contains no cells. In production code, it is often safer to refer to a named worksheet and explicit range rather than rely on whichever cell happens to be active. The following example demonstrates the early-exit structure using a fixed worksheet:
Public Sub CheckInput()
Dim inputSheet As Worksheet
' Stop with a clear message if the expected input is missing.
Set inputSheet = ThisWorkbook.Worksheets("Input")
If Len(CStr(inputSheet.Range("B2").Value)) = 0 Then
MsgBox "Enter a value in cell B2 before continuing."
Exit Sub
End If
MsgBox "The required input is present."
End Sub
The check only establishes that B2 is not blank after conversion to text. It does not prove that the value is valid for every later calculation. Add the checks your task actually requires, such as checking that a date is a date or that a number falls within an acceptable range. Keep messages specific so a user knows what to fix.
Exit Sub Inside Loops and Conditions
If Exit Sub is inside a For, For Each, or Do loop, it ends the whole Sub immediately. It does not merely stop the current loop iteration. This can be useful when a serious problem means no further work should happen, but it is a frequent source of accidental incomplete processing.
To stop only a For loop and continue running the procedure afterward, use Exit For. To leave a Do loop, use Exit Do. For example, if a procedure scans several rows and wants to stop scanning after finding a match, Exit For allows statements after the loop to run. Replacing it with Exit Sub would skip those statements too.
Likewise, an If block does not have its own exit statement. Use the appropriate structure: allow the block to finish, use Else for an alternate path, or use Exit Sub if the entire procedure should end. Read the lines after the exit point carefully; they will not run on that path.
Exit Sub Compared With End and Other Exit Statements
VBA has several ways to leave code, and their scope differs. Choose the one matching the block or procedure you intend to leave:
Exit Subends the current Sub procedure.Exit Functionends the current Function procedure. A Function that must provide a result should assign its return value before it exits.Exit Forleaves the currentForloop, then continues after that loop.Exit Doleaves the currentDoloop, then continues after that loop.Endis a forceful statement that halts VBA execution rather than returning normally from just the current Sub. It can interrupt other running code and bypass orderly cleanup, so it is not a substitute forExit Subin ordinary macro logic.
For instance, a Sub can call another Sub. If the inner procedure executes Exit Sub, only the inner procedure ends; the outer procedure resumes after its call. It does not cancel the caller or all other macros. This is why Exit Sub is usually the safer, more precise choice than End.
Cleanup, Error Handling, and Safe Early Exits
An early exit skips every later statement in the procedure. That matters if the procedure has temporarily changed Excel settings, opened a file, created an object that needs closing, or otherwise has cleanup work to do. For example, if code turns off screen updating and then exits before turning it back on, Excel may remain in an inconvenient state.
When every path must restore a setting or release a resource, send early paths to a shared cleanup label rather than placing Exit Sub above the cleanup. This pattern also provides a place to handle an error. The example saves and restores the existing screen-updating setting and reports an error after restoration:
Public Sub UpdateReportSafely()
Dim oldScreenUpdating As Boolean
Dim errorNumber As Long
Dim errorText As String
' Preserve Excel's current setting before changing it.
oldScreenUpdating = Application.ScreenUpdating
On Error GoTo CleanUp
Application.ScreenUpdating = False
If ThisWorkbook.Worksheets("Report").Range("A1").Value = "" Then
GoTo CleanUp
End If
ThisWorkbook.Worksheets("Report").Range("A1").Font.Bold = True
CleanUp:
' Save error details before showing a message.
errorNumber = Err.Number
errorText = Err.Description
Application.ScreenUpdating = oldScreenUpdating
If errorNumber <> 0 Then
MsgBox "The update failed: " & errorText & " (" & errorNumber & ")"
End If
End Sub
In this example, GoTo CleanUp is deliberate: the blank-cell path still restores the setting. The error handler also transfers control to the same label if a statement raises a run-time error. A cleanup routine should be designed for the resources your actual macro uses; restoring one Excel setting does not handle every possible cleanup need. If cleanup itself can fail, that possibility needs its own handling.
Common Problems and How to Diagnose Them
If a macro appears to stop unexpectedly, search for every Exit Sub in the procedure and check which condition leads to it. A message box immediately before an exit, or a breakpoint on the exit line, can show whether the path is being taken. In the Visual Basic Editor, use Debug > Compile VBAProject to catch compile errors, then step through the code with F8. A compile error is different from an intentional early exit: it prevents valid execution until corrected.
- Code after the exit does not run: This is the intended behavior. Move the exit below required statements or use a branch that allows the later work to proceed.
- The wrong loop behavior: Use
Exit FororExit Doif only the loop should stop. - A setting stays changed: Route early paths through cleanup, or postpone changing the setting until after validation.
- A caller does not continue: Check whether the caller itself has another exit, an error, or a condition that prevents its next statement from running. An exit in a called Sub alone does not end the caller.
- A procedure name is not recognized: Confirm that the code is in a standard module or the correct object module and that the procedure is accessible from the calling code.
Running and Saving VBA Macros in Excel
In Excel for Microsoft 365 on Windows, press Alt+F11 to open the Visual Basic Editor. Alt+F8 opens the Macro dialog for running available macros. On a Mac, Option+F11 and Option+F8 are the corresponding shortcuts on many keyboards; some require holding Fn as well, depending on keyboard settings. You can also use the Developer tab’s Visual Basic and Macros commands. If Developer is not visible, enable the Developer tab through Excel’s ribbon settings.
To keep VBA code, save the workbook in a macro-enabled format such as .xlsm. Excel for the web can open a macro-enabled workbook, but it cannot create, run, or edit VBA macros; use the desktop Excel application for those tasks. Treat files containing macros cautiously: only enable macros in files from sources you trust, and do not lower macro security just to make an unfamiliar file run.
Frequently Asked Questions
Does Exit Sub stop the whole macro? No. It ends only the current Sub. If another Sub called it, the caller continues at the line after the call unless its own logic or an error stops it.
Can I use Exit Sub in an If statement? Yes. If the condition is true and VBA reaches that statement, the entire current Sub ends. The rest of the If block and all later statements in that Sub are skipped.
What is the difference between Exit Sub and End Sub? Exit Sub is an explicit early exit that can appear before the procedure’s end. End Sub marks the end of the procedure in the code; reaching it ends the Sub normally.
Can I use Exit Sub in a Function? A Function should use Exit Function to leave early. If it must return a useful result, assign that result to the Function’s name before exiting; otherwise the returned value may be the default value for its type.
Can Exit Sub undo changes already made? No. It only stops later code from running. Changes made before the exit remain, and Ctrl+Z does not undo macro actions. Save a copy before running a macro that modifies important data.
Related
- How to Number Lines in Excel: 4 Reliable Methods
- How to Not Copy Hidden Cells in Excel When Pasting
- How to Normalize Cell Size in Excel for a Consistent Layout
Try it: the Column Letter to Number: aA is 27, XFD is 16,384. Converts both ways.
More in VBA & macros
- Excel VBA Font Color: Set, Read, and Fix ItIn Excel VBA, set a cell’s font color with the Font.Color property, usually by assigning an RGB value—for…
- Excel VBA AutoFill: Methods, Examples, and FixesIn Excel VBA, use the Range.AutoFill method to extend a formula, value pattern, or formatting into a destination…
- VBA Macros in Google Sheets: What Works InsteadNo. Google Sheets cannot run VBA macros: VBA is Microsoft Excel’s programming language, and Sheets uses Google Apps…
- VBA Range.Delete: Remove Cells, Rows, or ColumnsIn Excel VBA, use the Delete method to remove cells, rows, or columns: for example, Range("B2:C5").Delete Shift:=xlShiftUp deletes…
- Outlook VBA: How to Pull and Export Mail DataTo pull mail data with VBA, use classic Outlook for Windows’ object model to select a folder, loop…
- Excel UserForm Keeps Changing Size? Causes and FixesAn Excel UserForm usually changes size because VBA or its AutoSize setting changes its dimensions, or because Windows…
Sources: Function behaviour and menu paths: Microsoft Support documentation for Excel. Method & sources
Spotted an error in this guide? Let us know.