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]
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!
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
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.
Often we think about beginnings not endings. It is only when we get somewhere it is when we realize we hadn’t thought through our destination. Same goes for writing VBA macros. Fortunately the VBA End statement is here to save the day and help us put that full-stop in the right place. Today I want to share a cool VBA tip for properly ending your VBA macros i.e. how to abort a macro.
The VBA End statement ends the execution of a certain VBA scope.
VBA End statement
The VBA End Statement is used to mark the end of a specific VBA scope:
'End a Function definition, Sub definition, With statement, Select statement, Type definition, Enum defition, If statement End [Function | Sub | With | Select | Type | Enum | If ]
You can End a Function, a conditional If statement, mark the End of an VBA Enum or VBA Type. The End statement cannot be used within loop, function or procedure to end its execution prematurely. For that we need to use the VBA Exit statement instead.
So to summarize – End marks the end of a specific VBA scope similarly like { } brackets in C# or tabs in Python.
VBA Exit statement
The VBA Exit Statement is used to exit a particular scope earlier than defined by the VBA End Statement.
'Exit earlier a Do-While/Until loop, For loop, Function/Sub, Select statement Exit [ Do | For | Function | Select | Sub ]
In should be used to end the execution of a loop, function or procedure earlier.
See example below to understand the difference between VBA End and VBA Exit:
Sub SomeProcedure '... If iWantToExit Then Exit Sub 'if the statement is True this will stop any further execution of this Sub End if '... End Sub 'This ends the statement of the Sub procedure
Exiting VBA Functions or Procedures
Sometimes however we want to end the execution of a function or procedure early, simply by leaving the current execution scope.
Exit Sub
Ending Sub procedures is very useful. Instead of using the End statement we need to use the VBA Exit statement.
Sub SomeSub() '... 'Your code here '... Exit Sub 'Exit the Sub without executing code below '... 'This code will not be executed '... End Sub
Exit Function
Similarly for Functions we need to use the Exit statement instead of End.
Function SomeFunction() as Integer '... 'Your code here SomeFunction = 1 Exit Function 'Exit the Function without executing code below '... 'This code will not be executed SomeFunction = 2 End Function
The result of the VBA Function above is 1 not 2.
Exit VBA Loop
You can also use Exit to exit a VBA Loop statement:
For i = 0 to 10 '... If wantToexit = True Then Exit For 'Will exit For loop without executing code below before Next i End if '... Next i
The result of the VBA Function above is 1 not 2.
End VBA macro / Reset VBA macro
Now here is the trick I want to sell you today. The Exit statement above will allow you to leave the scope of your current VBA Function or VBA Sub. It will not however end the execution of your entire macro. A simple example below:
Sub Main() Call SomeSub 'Code will execute Debug.Print "Main: Hello after Exit Sub!" End Sub Sub SomeSub() Exit Sub 'Code will not execute Debug.Print "SomeSub: Hello after Exit Sub!" End Sub
The result:
So you see Exit Sub exiting only the the current scope of the running VBA Sub procedure and not the entire macro!
End – as simple as that
How to exit the execution of the entire macro (the Main Sub)? A simple End will do…
Sub Main() Call SomeSub 'Code will not execute Debug.Print "Main: Hello after Exit Sub!" End Sub Sub SomeSub() End 'Code will not execute Debug.Print "SomeSub: Hello after Exit Sub!" End Sub
The result:
The End statement ends the execution of the ENTIRE MACRO.
Use End carefully!
As Andy Pope has rightfully corrected me, the End statement needs to be used with care. As there are consequences…
The VBA End statement works a lot like the VBA Reset button. This is what happens:
- Object events will not be invoked e.g. the Unload, QueryUnload, or Terminate events
- Any running Visual Basic code will be stopped – that means Timers and other running code
- Object references held by other programs are invalidated – if any application is holding a reference to a VBA object it will be invalidated and inaccessible
- Closes any open dialogs / forms (e.g. UserForm or MsgBox)
Using End is a lot like pulling a hand brake in a car. It stops the car, but often so abruptly it might cause it to crash.
Say I have a button embedded into my spreadsheet that launches some VBA function.
Private Sub CommandButton1_Click()
SomeVBASub
End Sub
Private Sub SomeVBASub
DoStuff
DoAnotherStuff
AndFinallyDothis
End Sub
I’d like to have an opportunity to have some sort of a «cancel» button that would stop SomeVBASub
execution at an arbitrary moment, and I’m not into involving Ctrl+Break
here, ’cause I’d like to do it silently.
I guess this should be quite common issue, any ideas?
Thanks.
asked Oct 20, 2010 at 16:02
Kirill LeontevKirill Leontev
10.6k7 gold badges43 silver badges49 bronze badges
Add another button called «CancelButton» that sets a flag, and then check for that flag.
If you have long loops in the «stuff» then check for it there too and exit if it’s set. Use DoEvents inside long loops to ensure that the UI works.
Bool Cancel
Private Sub CancelButton_OnClick()
Cancel=True
End Sub
...
Private Sub SomeVBASub
Cancel=False
DoStuff
If Cancel Then Exit Sub
DoAnotherStuff
If Cancel Then Exit Sub
AndFinallyDothis
End Sub
answered Oct 20, 2010 at 16:10
Jamie TreworgyJamie Treworgy
23.8k8 gold badges75 silver badges119 bronze badges
3
How about Application.EnableCancelKey — Use the Esc button
On Error GoTo handleCancel
Application.EnableCancelKey = xlErrorHandler
MsgBox "This may take a long time: press ESC to cancel"
For x = 1 To 1000000 ' Do something 1,000,000 times (long!)
' do something here
Next x
handleCancel:
If Err = 18 Then
MsgBox "You cancelled"
End If
Snippet from http://msdn.microsoft.com/en-us/library/aa214566(office.11).aspx
answered Oct 20, 2010 at 16:17
Or, if you want to avoid the use of a global variable you could use the rarely used .Tag
property of the userform:
Private Sub CommandButton1_Click()
Me.CommandButton1.Enabled = False 'Disabling button so user cannot push it
'multiple times
Me.CommandButton1.caption = "Wait..." 'Jamie's suggestion
Me.Tag = "Cancel"
End Sub
Private Sub SomeVBASub
If LCase(UserForm1.Tag) = "cancel" Then
GoTo StopProcess
Else
'DoStuff
End If
Exit Sub
StopProcess:
'Here you can do some steps to be able to cancel process adequately
'i.e. setting collections to "Nothing" deleting some files...
End Sub
answered Mar 25, 2014 at 19:02
simpLE MAnsimpLE MAn
1,56213 silver badges22 bronze badges
what jamietre said, but
Private Sub SomeVBASub
Cancel=False
DoStuff
If not Cancel Then DoAnotherStuff
If not Cancel Then AndFinallyDothis
End Sub
answered Oct 20, 2010 at 16:13
BethBeth
9,5131 gold badge23 silver badges43 bronze badges
I do this a lot. A lot.
I have got used to using «DoEvents» more often, but still tend to set things running without really double checking a sure stop method.
Then, today, having done it again, I thought, «Well just wait for the end in 3 hours», and started paddling around in the ribbon. Earlier, I had noticed in the «View» section of the Ribbon a «Macros» pull down, and thought I have a look to see if I could see my interminable Macro running….
I now realise you can also get this up using Alt-F8.
Then I thought, well what if I «Step into» a different Macro, would that rescue me? It did
It also works if you step into your running Macro (but you still lose where you’re upto), unless you are a very lazy programmer like me and declare lots of «Global» variables, in which case the Global data is retained
K
answered Jul 16, 2014 at 14:26
~ For those using custom input box
Private Sub CommandButton1_Click()
DoCmd.Close acForm, Me.Name
End
End Sub
answered Apr 1, 2015 at 10:51
Paul ClintPaul Clint
911 gold badge2 silver badges10 bronze badges
This is an old post, but given the title of this question, the END option should be described in more detail. This can be used to stop ALL PROCEDURES (not just the subroutine running). It can also be used within a function to stop other Subroutines (which I find useful for some add-ins I work with).
As Microsoft states:
Terminates execution immediately. Never required by itself but may be placed anywhere in a procedure to end code execution, close files opened with the Open statement, and to clear variables*. I noticed that the END method is not described in much detail. This can be used to stop ALL PROCEDURES (not just the subroutine running).
Here is an illustrative example:
Sub RunSomeMacros()
Call FirstPart
Call SecondPart
'the below code will not be executed if user clicks yes during SecondPart.
Call ThirdPart
MsgBox "All of the macros have been run."
End Sub
Private Sub FirstPart()
MsgBox "This is the first macro"
End Sub
Private Sub SecondPart()
Dim answer As Long
answer = MsgBox("Do you want to stop the macros?", vbYesNo)
If answer = vbYes Then
'Stops All macros!
End
End If
MsgBox "You clicked ""NO"" so the macros are still rolling..."
End Sub
Private Sub ThirdPart()
MsgBox "Final Macro was run."
End Sub
answered Jun 19, 2019 at 1:33
pgSystemTesterpgSystemTester
8,7802 gold badges22 silver badges49 bronze badges