In VBA, you can exit a Sub or Function, by using the Exit Sub or Exit Function commands.
Exit Sub
Exit Function
When the execution of the code comes to Exit Sub or Exit Function, it will exit a Sub or Function and continue with any other code execution.
If you want to learn how to exit a Sub on Error, click on this link: VBA On Error Exit Sub
If you want to learn how to end a whole code execution, click on this link: VBA End
Exit a Sub in VBA
You will see on the example what happens when we use the Exit Sub command in a Sub. We created a Sub ExitSub, which has the Exit Sub command inside. The Sub CallExitSub calls this Sub. Here is the code:
Private Sub ExitSub()
Dim i As Integer
For i = 1 To 10
If i = 5 Then
Exit Sub
MsgBox "The value of i is" & i
End If
Next i
End Sub
Private Sub CallExitSub()
Call ExitSub
MsgBox "Exit Sub"
End Sub
In the ExitSub, we first enter the For Loop if the value of i is less than 10:
For i = 1 To 10
Next i
After that we check if the value of i is equal to 5, using the If command. If the value is 5, we want to exit the Sub and return the Message box with the value of i:
If i = 5 Then
Exit Sub
MsgBox "The value of i is" & i
End If
If the condition is not met, the following statement increases i by 1 and enters in the For loop again:
Next i
In the CallExitSub, we first call the Sub ExitSub:
Call ExitSub
After that we return the Message box:
MsgBox "Exit Sub"
If you run the CallExitSub, it will first call the ExitSub. If you execute this code in the debug mode, you will see that it will go through the loop 5 times. In the 5th iteration, the value of the variable i becomes 5 and the code enters in the If body. Now the Sub ExitSub is exited and returned to the CallExitSub. The next line is MsgBox “Exit Sub”:
As you can see, the ExitSub is exited right after Exit Sub command, so the MsgBox “The value of i is” & i will be never executed.
Exit a Function in VBA
Exiting a function in VBA is similar to exiting a Sub, just the command is Exit Function. In the example, we created the ExitFunc which returns an integer. The Sub CallExitFunction calls this function. Here is the code:
Private Function ExitFunc() As Integer
Dim i As Integer
For i = 1 To 10
If i = 5 Then
ExitFunc = i
Exit Function
End If
Next i
End Function
Private Sub CallExitFunction()
Dim intFunc As Integer
intFunc = ExitFunction()
MsgBox "The value of intFunc is " & intFunc
End Sub
In the ExitFunc, we first enter the For Loop if the value of i is less than 10:
For i = 1 To 10
Next i
After that we check if the value of i is equal to 5, using the If command. If the value is 5, we assign the value of i to the function result and exit the function:
If i = 5 Then
ExitFunc = i
Exit Function
End If
If the condition is not met, the following statement increases i by 1 and enters in the For loop again:
Next i
In the CallExitFunction, we first call the function ExitFunc: To do that we have to declare the variable intFunc type integer and assign the result of the ExitFunc function to it:
Dim intFunc As Integer
intFunc = ExitFunction()
After that we return the Message box with the value of intFunc:
MsgBox "The value of intFunc is " & intFunc
If you run the CallExitFunction, it will first call the function ExitFunc. If you execute this code in the debug mode, you will see that it will go through the loop 5 times. In the 5th iteration, the value of the variable i becomes 5 and the code enters in the If body. Now the value of the ExitFunc becomes i and the function is exited and returned to the CallExitFunction. The next line is MsgBox “The value of intFunc is ” & intFunc:
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!
Permalink
Cannot retrieve contributors at this time
title | keywords | f1_keywords | ms.prod | ms.assetid | ms.date | ms.localizationpriority |
---|---|---|---|---|---|---|
Exit statement (VBA) |
vblr6.chm1008916 |
vblr6.chm1008916 |
office |
2a1f4605-8220-c5b1-3760-c710f0535aa8 |
12/03/2018 |
medium |
Exits a block of Do…Loop, For…Next, Function, Sub, or Property code.
Syntax
Exit Do
Exit For
Exit Function
Exit Property
Exit Sub
The Exit statement syntax has these forms:
Statement | Description |
---|---|
Exit Do | Provides a way to exit a Do…Loop statement. It can be used only inside a Do…Loop statement. Exit Do transfers control to the statement following the Loop statement. When used within nested Do…Loop statements, Exit Do transfers control to the loop that is one nested level above the loop where Exit Do occurs. |
Exit For | Provides a way to exit a For loop. It can be used only in a For…Next or For Each…Next loop. Exit For transfers control to the statement following the Next statement. When used within nested For loops, Exit For transfers control to the loop that is one nested level above the loop where Exit For occurs. |
Exit Function | Immediately exits the Function procedure in which it appears. Execution continues with the statement following the statement that called the Function. |
Exit Property | Immediately exits the Property procedure in which it appears. Execution continues with the statement following the statement that called the Property procedure. |
Exit Sub | Immediately exits the Sub procedure in which it appears. Execution continues with the statement following the statement that called the Sub procedure. |
Remarks
Do not confuse Exit statements with End statements. Exit does not define the end of a structure.
Example
This example uses the Exit statement to exit a For…Next loop, a Do…Loop, and a Sub procedure.
Sub ExitStatementDemo() Dim I, MyNum Do ' Set up infinite loop. For I = 1 To 1000 ' Loop 1000 times. MyNum = Int(Rnd * 1000) ' Generate random numbers. Select Case MyNum ' Evaluate random number. Case 7: Exit For ' If 7, exit For...Next. Case 29: Exit Do ' If 29, exit Do...Loop. Case 54: Exit Sub ' If 54, exit Sub procedure. End Select Next I Loop End Sub
See also
- Data types
- Statements
[!includeSupport and feedback]
Home / VBA / VBA Exit Sub Statement
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.
To start with, make sure you have a good understanding of what a function is and how it works. You can get a great overview in my articles here:
What is “You’ve Entered too Many Arguments”?
How Do You Fix “Compile Error: Argument not optional”?
How do you stop a function from executing fully?
There may be situations in which we need to stop executing a function and to immediately return to the point of function call without executing the rest of the code in the function. This is where the statement “Exit Function” comes into the picture. This statement serves that purpose without causing any compile or runtime errors.
Sample Scenarios
Let us consider the following examples one-by-one.
Example 1
A function is developed to check if a particular person’s name exists in a list of 1000 members. The list is available on a webpage and there is no provision to directly find the existence of that name in the list.
We’ll use a loop to compare the person’s name against each of the names in the list. Once we find that it’s in the 400th position on the list, there is no need to continue with the comparison against the other items. That would be a mere waste of time.
In general, we’d use the “Exit for” statement here to skip the rest of the iterations in the loop. This “Exit For” statement takes the program control to the line after the respective “Next” statement of the “For” loop. But using “Exit Function” statement skips all the statements in the function and takes us back to the function call.
Sub Exit_Function_demo() 'Calling function / function call Call findme("Wales") 'Just a statement that prints after the function call Debug.Print "Post function call" End Sub Function findme(full_name) ' A for loop to iterate through all the items in the sheet in col 1 For i = 1 To 10 ' inside loop 'Store the cell valur in a variable and print it. new_value = Cells(i, 1).Value Debug.Print new_value 'Compare the paramter passed with the cell value to check condition If new_value = full_name Then 'Print if found Debug.Print "The name " & full_name &" exists in the list in the row number " & i 'Exit the function Exit Function End If Next 'This will execute only if the value passed in te parameter is not in the list. Debug.Print "Outside Loop" End Function
Example 2
Let’s imagine a function that calculates maturity amount and interest for fixed deposits based on the age and gender of our customers. For the sake of this example, we are collecting age and gender to define the interest rate. The logic uses this criteria:
- Males above or equal to 60 yrs = Senior Citizens
- Females above or equal to 58 yrs = Senior Citizens
- Rate of Interest for Senior Citizens = 9%
- Rate of Interest for non-Senior Citizens = 6%
This way, since we get the age first, if it is greater than or equal to 60, we can completely bypass getting gender as an input. The “Exit Function” statement is of use here.
Sub calc_mat_amt() 'Declare variables Dim p, n, roi 'Initialize variable values. Receive input for customer's age and gender p = 10000 n = 1 gender = InputBox("Input gender of the customer") age = InputBox("Input age of the customer") 'Call the function to find roi roi = find_roi(gender, age) 'calculate the maturity amount matamt = p + ((p * n * r) / 100) End Sub Function find_roi(gender, age) 'first condition is common to males and females If age > 59 Then find_roi = 9 Debug.Print "Part 1 executed" Exit Function Else ' condition to filter out the females who are senior citizens If gender = "Female" And age > 57 Then find_roi = 9 Debug.Print "Part 2 executed" Exit Function Else ' all other non- senior citizens find_roi = 6 Debug.Print "Part 3 executed" Exit Function End If End If ' Once the function is exited, the blow line would not be printed. Debug.Print "this part of the function is skipped" End Function
Example 3
Now let us see a different example. Assume that the end user who is going to run this procedure wants to check his horoscope.
Sub astro() 'function call Call check_my_horoscope 'Print a statement after function call Debug.Print "Function call is executed" End Sub Function check_my_horoscope() Dim belief, dob 'Find the interest of the user belief = MsgBox("Do you believe in astrology?", vbYesNo) 'Do not allow user to proceed further if he has no interest. 'Value for vbNo is 7 If belief = 7 Then Debug.Print ("This module is not for you") Exit Function End If 'Get the date of birth of the user dob = InputBox("Enter your date of birth") 'Do not allow the user to proceed further if the user enters and invalid dob. If IsDate(dob) = False Then Debug.Print ("Invalid Dob. Exiting module. Try again later") Exit Function End If 'Rest of the horoscope checking code Debug.Print "Rest of the code goes here. " End Function
Output for the above code with input values “Yes” and “45”
Output of the same code with “No” as the first input ( for that message box).
Example 4
Here is another piece of code that displays a food menu for each day of the week. Run the code with different inputs to understand how it works.
Sub hotel() 'code to call the function Call food_menu End Sub Function food_menu() 'receive the input from the user strWeekday = InputBox("Enter the day") 'menu items for each day . We exit only if it is a holiday or an invalid day If LCase(strWeekday) = "sunday" Then Debug.Print "The Restaurant is closed on Sundays !" Exit Function ElseIf LCase(strWeekday) = "monday" Then Debug.Print "Tomato Rice is available at 3$" ElseIf LCase(strWeekday) = "tuesday" Then Debug.Print "Chappatis are available at 1$ each" ElseIf LCase(strWeekday) = "wednesday" Then Debug.Print "Lemon Rice is available at 3$" ElseIf LCase(strWeekday) = "thursday" Then Debug.Print "Idlies are available at 1$ each" ElseIf LCase(strWeekday) = "friday" Then Debug.Print "Noodles is available at 1$" ElseIf LCase(strWeekday) = "saturday" Then Debug.Print "Burger is available at 2$" Else Debug.Print "The day entered is invalid" Exit Function End If 'validate the purchase purchase = MsgBox("Do you wish to buy?", vbYesNo) 'end the module if user doesn't want to buy If purchase = 7 Then Debug.Print "Thank you for the enquiry. You will exit the module now" Exit Function End If 'generate a token and greet the user if he is interested to buy. 'code to generate a token Debug.Print "Collect your token.Pay at the counter. Bon appétit " End Function
Conclusion
VBA offers numerous methods to manage the movement of runtime control in our code. For example:
- Loops like For, foreach, do until, while
- Statements like “Exit for”, “Exit do”
- If conditions with a variety of structures like simple if, else if, nested if
However, there might be situations where you need to stop or restrict the flow of execution in a specific direction without using any of these features. That’s where “Exit Function” statement comes to the rescue and simplifies our code.
See also:
Else Do Nothing
Excel VBA Exit Sub Procedure
Exit Sub statement exits the sub procedure earlier than the defined lines of VBA codes. First, we need to apply a logical test to exit the sub procedure.
Table of contents
- Excel VBA Exit Sub Procedure
- Examples
- Example #1
- Example #2 – On Error Exit the Subprocedure
- Recommended Articles
- Examples
Let us construct this in simple terms.
Sub MacroName() '... 'Some code here '... Exit Sub 'Exit the Sub without executing further lines of code below '... 'This code will be ignored '... End Sub
Examples
You can download this VBA Exit Sub Excel Template here – VBA Exit Sub Excel Template
Example #1
For a better example, look at the below code.
Code:
Sub Exit_Example1() Dim k As Long For k = 1 To 10 Cells(k, 1).Value = k Next k End Sub
The above code will insert serial numbers from 1 to 10 in cells A1 to A10.
Now, we want to insert only 5 serial numbers. As soon as the variable “k” value becomes 6, we want to exit the sub.
We will have to add the logical test in excelA logical test in Excel results in an analytical output, either true or false. The equals to operator, “=,” is the most commonly used logical test.read more as IF k = 6 Then Exit Sub.
Code:
Sub Exit_Example1() Dim k As Long For k = 1 To 10 If k = 6 Then Exit Sub 'As soon as k value becomes 6 it will ignore all the codes and exit Cells(k, 1).Value = k Next k End Sub
Now, run the code line by line. Finally, press the F8 key to start the proceedings.
As of now, the k value is zero.
To change the k value to 1, press the F8 key again.
So, the k value is 1. Our code keeps running and will insert 1 to cell A1. Like this, keep running the loop until the value of k becomes 6.
Now, the value of k is 6. The line of code is about to execute our logical test to exit the subprocedure. If we press the F8 key one more time, it will straight go the entire sub procedure only.
As we can see, it has highlighted the word “Exit Sub.” Upon pressing the F8 key, it will exit the sub procedure without going to the word “End Sub.”
Example #2 – On Error Exit the Subprocedure
We can also exit the sub procedure when we get the error values. For example, consider the below data for dividing the number1 from 2.
Below is the code to get the division of two numbers.
Code:
Sub Exit_Example2() Dim k As Long For k = 2 To 9 Cells(k, 3).Value = Cells(k, 1).Value / Cells(k, 2).Value Next k End Sub
As we know, we cannot divide any number by zero. So, if we attempt to do that, we will get the error “Run-time error ’11’: Division by zero.”
To avoid this, as soon as we encounter any error, we will immediately mention my macro to exit the sub procedure. The below code is one such case.
Code:
Sub Exit_Example2() Dim k As Long For k = 2 To 9 On Error GoTo ErrorHandler Cells(k, 3).Value = Cells(k, 1).Value / Cells(k, 2).Value Next k ErrorHandler: Exit Sub End Sub
In the above example, we have mentioned the statement “On Error Goto ErrorHandler.” Here, the word “ErrorHandler” is the label we have assigned. As you can see at the bottom of the code, we have mentioned the brand as:
ErrorHandler:
Exit Sub
As soon as the code encounters an error, it will push the code to jump to the label, and the brand has the “Exit Sub” statement so that it will exit the subprocedure.
Now, we will run the code. First, it will calculate the division until it finds an error.
As you can see in cell C7, it has encountered an error as “Division by zero,” so it has exited the subprocedure. However, exiting the sub procedure is always dangerous without informing the user. Therefore, we can include a small message box to notify the user of the error.
Code:
Sub Exit_Example2() Dim k As Long For k = 2 To 9 On Error GoTo ErrorHandler Cells(k, 3).Value = Cells(k, 1).Value / Cells(k, 2).Value Next k ErrorHandler: MsgBox "Error has Occured and the error is:" & vbNewLine & Err.Description Exit Sub End Sub
The above code will show the error message and then exit the subprocedure. While running code, if an error occurs, it will show the message box in VBAVBA MsgBox function is an output function which displays the generalized message provided by the developer. This statement has no arguments and the personalized messages in this function are written under the double quotes while for the values the variable reference is provided.read more like below.
It is more of a reliable way of exiting the Sub procedure.
Recommended Articles
This article is a guide to VBA Exit Sub Procedure. Here, we discuss how to exit the VBA sub procedure when an error occurs in the code with an example and downloadable Excel sheet. You can learn more about VBA from the following articles: –
- VBA On Error GoTo
- VBA Delete Sheet
- Break Points in Excel VBA
- Do Until Loop in Excel VBA
- VBA ByRef Argument Type Mismatch