VBA On Error Exit Sub
Written by
Reviewed by
In VBA, you can program your code to Exit a Sub whenever an error is encountered. To do this, use On Error GoTo and Exit Sub.
On Error Goto tells VBA that when an error is encountered to “Go To” a specific section of your code. Ex:
On Error GoTo ErrorHandler
From within that section you can then tell VBA to Exit Sub to exit the sub procedure:
ErrorHandler:
Exit Sub
Read on, to see these lines of code in action…
Exit a Sub on Error in VBA
In this example, we will generate an error by dividing by zero:
i = 5 / 0
See the full code below. When VBA reads the error, it will “goto” the ErrorHandler section of code and exit:
Sub TestError ()
Dim i As Integer
On Error GoTo ErrorHandler
i = 5 / 0
'Do Something with i
MsgBox i
Exit Sub
ErrorHandler:
MsgBox "If error, then exit the Sub"
Exit Sub
End Sub
To specify error handling, you first need to declare On Error GoTo statement. It should be declared at the beginning of a Sub:
On Error GoTo ErrorHandler
After that you need to declare the error handling code. It is usually at the end of the code:
ErrorHandler:
MsgBox "If error, then exit the Sub"
Exit Sub
We add the “Exit Sub” above the ErrorHandler because we only want to run the ErrorHandler code if there’s an error.
Exit Sub
ErrorHandler:
MsgBox "If error, then exit the Sub"
Exit Sub
End Sub
If you run the Sub, it will come to an error because of division by zero. In that moment the error handling code will be executed. The message box appears and the Sub is exited.
If you want to learn how to end code execution in VBA, click on this link: VBA End
If you want to learn how to exit a Sub or Function, click on this link: VBA Exit Sub or Function
VBA Coding Made Easy
Stop searching for VBA code online. Learn more about AutoMacro - A VBA Code Builder that allows beginners to code procedures from scratch with minimal coding knowledge and with many time-saving features for all users!Learn More!