VBA On Error Exit Sub

Associated Files Download Links

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:

From within that section you can then tell VBA to Exit Sub to exit the sub procedure:

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:

See the full code below.  When VBA reads the error, it will “goto” the ErrorHandler section of code and exit:

To specify error handling, you first need to declare On Error GoTo statement. It should be declared at the beginning of a Sub:

After that you need to declare the error handling code. It is usually at the end of the code:

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.

vba on error exit sub

Image 1. VBA On Error Exit Sub

 

 

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