VBA Exit Sub is a statement that you use to exit a sub-procedure or a function. As you know, each line is a macro executes one after another, and when you add the “Exit Sub” VBA, exit the procedure without running the rest of the code that comes after that. It works best with loops and the message box.
Using Exit Sub Statement in VBA
- First, decide on which line you want to add the “Exit Sub”.
- After that, check the structure of the code that will get executed when you run the code.
- Next, enter the “Exit Sub”.
- In the end, it’s better to have comment that describes why you are using the “Exit Sub” statement.
Note: In a VBA function procedure, the statement that you need to use is “Exit Function”.
Use Exit Sub with a Message Box and Input Box
Let’s say you want to get input from the user with an input box and exit the procedure if the user’s reply is not a number (consider the following example).
In the above code, you have ISNUMERIC that checks for the value entered in the input box if it’s a number or not, and if that value is not a number, it uses the Exit Sub statement to end the procedure after showing a message box.
Sub vba_exit_sub_example() If IsNumeric(InputBox("Enter your age.", "Age")) = False Then MsgBox "Error! Enter your Age in numbers only." Exit Sub Else MsgBox "Thanks for the input." End If End Sub
On Error Exit Sub
One of the best things about the “Exit Sub” you can use it to exit the procedure when an error occurs. Below is the code that divides a number with a zero that returns a “Run-time error ‘11’ “ and stops the execution.
Here you can use the GoTo statement to create an error handler with the “Exit Sub” to exit the procedure (consider the following code).
Sub vba_exit_sub_on_error() On Error GoTo iError Range("A1") = 10 / 0 iError: MsgBox "You can't divide with the zero." & _ "Change the code." Exit Sub End Sub
In the above code, you have an error handler, “iError” with a message box and then the “Exit Sub” Statement. When an error occurs during the calculation, the goto statement jumps to the error handler (VBA Error Handling), and it will exit the procedure.
If you are preparing for an interview, make sure to check out these VBA interview questions.