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!
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.
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
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
Синтаксис и программные конструкции VBA |
71 |
Проверьте, что будет, если поменять строку объявления функции:
Function fSum(nItem1 As Integer, nItem2 As Integer)
на другую:
Function fSum(byVal nItem1 As Integer, nItem2 As Integer)
Можно продемонстрировать компилятору VBA, что значение, возвращаемое функцией, нас совершенно не интересует. Для этого достаточно не заключать ее параметры в круглые скобки. Например, для нашей функции это может выглядеть так:
fSum 3, 2
Такой код будет работать совершенно нормально. Однако если нам потребуется все-таки узнать, что возвращает функция, то придется передаваемые ей параметры заключать в круглые скобки:
nResult = fSum(3, 2)
Для многих встроенных функций компилятор VBA в принципе не дает возможности игнорировать возвращаемое значение, заставляя помещать параметры в круглые скобки и принимать возвращаемое значение. В противном случае он сообщает о синтаксической ошибке.
С примерами вызова процедур и функций из кода мы уже сталкивались. Для этого достаточно записать имя процедуры или функции, передать ей необходимые параметры, а для функции еще и принять возвращаемое значение. Одни процедуры можно вызывать из других процедур. Но как дать пользователю возможность запустить самую первую процедуру?
В нашем распоряжении следующие возможности:
создать макрос (т. е. специальную процедуру, не принимающую параметров, в модуле NewMacros) и запустить его по имени, кнопке или комбинацией клавиш (см. разд. 1.4). Макрос затем может вызывать и другие процедуры;
создать форму и воспользоваться набором событий этой формы и элементов управления на ней (об этом будет рассказано в гл. 5) или просто элементом управления на листе Excel или документе Word;
назначить процедуре специальное имя (AutoExec(), AutoNew() и т. п.). Полный список таких специальных имен можно посмотреть в документации. Правда, поскольку раньше эти возможности активно использовались вирусами, в Office 2003 по умолчанию эти макросы запускаться не будут. Для того чтобы обеспечить им (и многим другим макросам) возможность
запуска, необходимо изменить установленный уровень безопасности в меню Сервис | Макрос | Безопасность или обеспечить цифровые подписи для ваших макросов;
вместо специального имени для макроса использовать событие: например, событие запуска приложения, событие открытия документа и т. п. Это рекомендованный Microsoft способ обеспечения автоматического запуска программного кода. Подробнее про работу с событиями будет рассказано в гл. 4 и 5;
можно запустить приложение из командной строки с параметром /m и именем макроса, например:
winword.exe /mMyMacros
Очень удобно в этом случае использовать ярлыки, в которых можно указать этот параметр запуска.
В VBA вполне допустима ситуация, когда функция запускает на выполнение саму себя. Однако подобных вызовов лучше избегать (по возможности заменяя их на циклы). Причина — проблемы с читаемостью и возможное (в случае бесконечного запуска) исчерпание оперативной памяти (переполнение стека), чреватое серьезными системными ошибками.
Для завершения выполнения процедуры в VBA предусмотрены конструкции End и Exit. Синтаксис их очень прост:
Exit Sub
End Sub
Делают они одно и то же — завершают работу текущей процедуры. Однако используются в разных ситуациях:
оператор End — это завершение работы процедуры после того, как все сделано. После оператора End код процедуры заканчивается;
оператор Exit — это немедленное завершение работы функции в ходе ее работы. Обычно помещается в блок оператора условного перехода, чтобы произвести выход, как только выяснилось, что функции по каким-то причинам дальше выполняться не нужно (например, дальше идет код обработчика ошибок).
Задание для самостоятельной работы 3.4: Работа с процедурами и функциями
ЗАДАНИЕ:
1.Создайте в модуле NewMacros шаблона Normal.dot новую функцию fMultiply(), которая бы:
Синтаксис и программные конструкции VBA |
73 |
•принимала в качестве входящих параметров два числа;
•перемножала их и возвращала полученное значение.
2.Создайте в модуле NewMacros шаблона Normal.dot новую процедуру AutoNew() со следующим кодом:
Public Sub AutoNew()
Dim nMult1 As Integer
Dim nMult2 As Integer
Dim nResult As Integer
nMult1 = CInt(InputBox(«Введите первое число: «)) nMult2 = CInt(InputBox(«Введите второе число: «)) nResult = 10
Selection.InsertAfter nResult Selection.Collapse wdCollapseEnd
End Sub
3.Измените процедуру AutoNew() таким образом, чтобы она передавала значения переменных nMult1 и nMult2 функции fMultiply() и принимала от нее значение для переменной nResult (это значение должно использоваться вместо жестко определенного значения 10).
4.Создайте в Word новый документ и убедитесь, что созданные вами процедуры и функции работают правильно.
5.Чтобы созданная вами процедура AutoNew() не мешала дальнейшей работе, закомментируйте весь ее код.
Ответ к заданию 3.4
1.Запустите Word и нажмите клавиши <Alt>+<F11>. В окне Project Explorer раскройте узел Normal | Modules и щелкните два раза левой кнопкой мыши на строке NewMacros.
2.Вставьте в модуль NewMacros следующие строки для функции
fMultiply():
Public Function fMultiply(nM1 As Integer, nM2 As Integer)
fMultiply = nM1 * nM2
End Function
3.Код для процедуры AutoNew() может выглядеть так (измененный код выделен полужирным):
Public Sub AutoNew()
Dim nMult1 As Integer
Dim nMult2 As Integer
Соседние файлы в предмете [НЕСОРТИРОВАННОЕ]
- #
- #
- #
- #
- #
- #
- #
- #
- #
- #
- #