Vba for excel exit sub

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”:

vba 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 exit function

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!
vba save as

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

  1. First, decide on which line you want to add the “Exit Sub”.
  2. After that, check the structure of the code that will get executed when you run the code.
  3. Next, enter the “Exit Sub”.
  4. 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

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

exit sub example 1.1

The above code will insert serial numbers from 1 to 10 in cells A1 to A10.

exit sub example 1.2

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

exit sub example 1.3

Now, run the code line by line. Finally, press the F8 key to start the proceedings.

exit sub example 1.8

As of now, the k value is zero.

exit sub example 1.4

To change the k value to 1, press the F8 key again.

exit sub example 1.5

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.

exit sub example 1.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.

exit sub example 1.7

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.

example 2.1

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

example 2.3

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.”

example 2.2

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

example 2.4

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.

exit sub example 2.5

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

example 2.6

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.

example 2.7

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

VBA Exit Sub

Introduction to VBA Exit Sub

Exit Sub seems like ending the subcategory by its name. But in reality, Exit Sub is used to jump out of the sub procedure altogether without letting the complete code getting completed. When we apply Exit Sub in between any code then only code before Exit sub gets run completely in VBA Excel. The code after Exit sub will get skipped and it will jump the entire code after to that. Exit Sub usually works better with Do-While Loop.

How to Apply Exit Sub Using VBA?

Let’s see the examples of Exit Sub in Excel VBA.

You can download this VBA Exit Sub Excel Template here – VBA Exit Sub Excel Template

Example #1 – VBA Exit Sub

Step 1: To apply Exit Sub we need a module. For that, go the VBA window. Click on Insert menu tab, we will get the list, from there select Module as shown below.

VBA Exit Module 1

Step 2: After that, a newly opened Module, write the subcategory in the name of VBA Exit Sub or in any other name as shown below.

Code:

Sub VBA_ExitSub1()

End Sub

VBA Exit Sub Example 1.1

Step 3: Define a variable Dim with any name, let’ say A. And give it Integer function to it as shown below.

Code:

Sub VBA_ExitSub1()

Dim A As Integer

End Sub

Excel VBA Exit Sub Example 1.2

Step 4: Now open a Do While Loop as shown below.

Code:

Sub VBA_ExitSub1()

Dim A As Integer
Do

While

End Sub

VBA Exit Sub Example 1.3

Step 5: In between Do While we write a simple code of comparison. Let’s DO addition of variable A with +1. Which means DO Addition for A with its own value +1. And run it till we get the +1 value for variable A.

Code:

Sub VBA_ExitSub1()

Dim A As Integer
Do
A = A + 1

While

End Sub

VBA Sub Example 1.4

Step 6: Now how much we want to add +1 to A will be defined in Loop While condition. Which says DO Loop will run following the condition of A + 1 while A is less than 100.

Code:

Sub VBA_ExitSub1()

Dim A As Integer
Do
A = A + 1

Loop While A < 100

End Sub

Sub Example 1.6

Step 7: Now we will need a message box (Which is optional) to see the output of Do While loop. For that insert MsgBox and give it to the variable A.

Code:

Sub VBA_ExitSub1()

Dim A As Integer
Do
A = A + 1

Loop While A < 100
MsgBox A

End Sub

 Example 1.6

Step 8: Now compile the code by pressing the F8 key to see if there is any bug in the code or not. Later run the entire code by pressing the Play button located below the menu bar as shown below. We will see the message box has given us the output as 100. Which means a value of A is less than 100 and formula which we defined in DO Loop says is the value of A is A + 1. So the answer is coming as 100.

VBA Exit Sub 1

Step 9: Now to apply the Exit Sub in performed Do While loop we need to add Exit Sub statement before Do Loop start or after we defined variable A as shown below.

Code:

Sub VBA_ExitSub1()

Dim A As Integer
Exit Sub
Do
 A = A + 1

Loop While A < 100
MsgBox A

End Sub

VBA 1.7

Now again compile the code and run, if no error found.

We will observe that we have not found any output. Which is because the code run is completed but it has skipped off to Do While loop completely giving no output in a message box.

Example #2 – VBA Exit Sub

Let’s consider another example. In this example, we will see how Exit Sub works on skipping the font color change. For we have some text at cell C3 as shown below. As we can see the text is in default blank color.

 VBA Exit Sub Example 2

Step 1: For this open a new module and give it Sub-Category in the name of VBA Exit sub or in any other suitable name as per your need.

Code:

Sub VBA_ExitSub2()

End Sub

Exit Example 2.1

Step 2: Select the range cell which has the text. Here our range cell will be cell C3.

Code:

Sub VBA_ExitSub2()

Range("C3").Select

End Sub

VBA Example sub 2.2

Step 3: As we need to change the font color, so in the next line of code select the Font and Color function simultaneously as shown below.

Code:

Sub VBA_ExitSub2()

Range("C3").Select
Selection.Font.Color =

End Sub

Example 2.3

Step 4: Now choose the color of font which we want to change. And the selection of color will be starting with vb as per VBA setting. Here, we are selecting Red as shown below.

Code:

Sub VBA_ExitSub2()

Range("C3").Select
Selection.Font.Color = vbRed

End Sub

Sub Example 2.5

Step 5: Now compile the entire the code in one go as the code is quite small and run it. We will see the color of the font at cell C3 is now changed to Red color from default Black.

VBA sub Exit 2

Step 6: Now to apply the Exit Sub here in font color change code, put the statement of Exit Sub before the Range cells selection line of code or between range cell selection (1st) and Font color (2nd) as shown below.

Code:

Sub VBA_ExitSub2()

Range("C3").Select

Exit Sub

Selection.Font.Color = vbRed

End Sub

 Sub Exit Example 2.3

Step 7: Now again run the code. This time we will notice that the font color of text at cell C3 doesn’t get changed to Red color as it changed earlier before placing Exit Sub statement.

VBA excel output

Step 8: We can convert the added Exit Sub statement into text by inserting a single inverted quote as shown below. By doing this, it will get converted into text. After that, the color of that line will be get changed to Green color.

Code:

Sub VBA_ExitSub2()

Range("C3").Select

'Exit Sub

Selection.Font.Color = vbRed

End Sub

VBA Green Sub

Pros of VBA Exit Sub

  • It saves time in re-writing a code again and again.
  • We can skip the portion of code which we don’t want to run.
  • It is applicable in all types of functions.
  • This is quite useful when working on big lines of code where we need to skip or jump some certain line of code.

Things to Remember

  • VBA Exit Sub works with all kind of codes and function but it works better with all kind of Loop, especially DO-WHILE Loop.
  • It jumps out from the portion of code and running only that much code which is before Exit Sub.
  • Exit and End Sub, both are different.
  • It skips and jumps out of the code without running it completely. And half run code doesn’t give any proper output.

Recommended Articles

This is a guide to VBA Exit Sub. Here we discuss how to use Excel VBA Exit Sub along with few practical examples and downloadable excel template. You can also go through our other suggested articles –

  1. VBA While Loop
  2. VBA Remove Duplicates
  3. VBA Data Types
  4. VBA Sleep

This is a bit outside the scope of your question, but to avoid any potential confusion for readers who are new to VBA: End and End Sub are not the same. They don’t perform the same task.

End puts a stop to ALL code execution and you should almost always use Exit Sub (or Exit Function, respectively).

End halts ALL exectution. While this sounds tempting to do it also clears
all global and static variables. (source)

See also the MSDN dox for the End Statement

When executed, the End statement resets allmodule-level variables and all static local variables in allmodules. To preserve the value of these variables, use the Stop statement instead. You can then resume execution while preserving the value of those variables.

Note The End statement stops code execution abruptly, without invoking the Unload, QueryUnload, or Terminate event, or any other Visual Basic code. Code you have placed in the Unload, QueryUnload, and Terminate events offorms andclass modules is not executed. Objects created from class modules are destroyed, files opened using the Open statement are closed, and memory used by your program is freed. Object references held by other programs are invalidated.

Nor is End Sub and Exit Sub the same. End Sub can’t be called in the same way Exit Sub can be, because the compiler doesn’t allow it.

enter image description here

This again means you have to Exit Sub, which is a perfectly legal operation:

Exit Sub
Immediately exits the Sub procedure in which it appears.
Execution continues with the statement following the statement that
called the Sub procedure. Exit Sub can be used only inside a Sub
procedure.

Additionally, and once you get the feel for how procedures work, obviously, End Sub does not clear any global variables. But it does clear local (Dim’d) variables:

End Sub
Terminates the definition of this procedure.

Содержание

  1. Оператор End
  2. Синтаксис
  3. Замечания
  4. Пример
  5. См. также
  6. Поддержка и обратная связь
  7. Прерывание процедур и функций VBA
  8. Оператор Exit
  9. Оператор End
  10. Оператор Exit (Visual Basic)
  11. Синтаксис
  12. Операторы
  13. Комментарии
  14. Пример 1
  15. Пример 2
  16. Пример 3
  17. Оператор Exit
  18. Синтаксис
  19. Замечания
  20. Пример
  21. См. также
  22. Поддержка и обратная связь
  23. Exit statement
  24. Syntax
  25. Remarks
  26. Example
  27. See also
  28. Support and feedback

Оператор End

Заканчивает процедуру или блок.

Синтаксис

End
End Function
End If
End Property
End Select
End Sub
End Type
End With

Синтаксис оператора End состоит из следующих форм:

Statement Описание
End Сразу же прекращает выполнение. Никогда не требуется сам по себе, но может быть размещен в любом месте процедуры для завершения выполнения кода, закрытия файлов, открытых с помощью инструкции Open , и для очистки переменных.
End Function Требуется для завершения инструкции Function .
End If Требуется для завершения блока Если. Затем. Оператор Else .
End Property Требуется для завершения процедуры Property Let, Property Get или Property Set .
End Select Требуется для завершения инструкции Select Case .
End Sub Требуется для завершения инструкции Sub .
End Type Требуется для завершения определения определяемого пользователем типа (оператор Type ).
End With Требуется для завершения инструкции With .

Замечания

При выполнении оператор End сбрасывает все переменные на уровне модуля и все статические локальные переменные во всех модулях. Чтобы сохранить значение этих переменных, используйте вместо этого инструкцию Stop . Вы сможет затем возобновить выполнение, сохранив значение этих переменных.

Оператор End резко останавливает выполнение кода, не вызывая событие Unload, QueryUnload или Terminate или любой другой код Visual Basic. Код, помещенный в события Unload, QueryUnload и Terminate форм и модулей класса, не выполняется. Объекты, созданные из модулей класса, уничтожаются, файлы, открытые с помощью инструкции Open , закрываются, а память, используемая программой, освобождается. Ссылки на объекты, удерживаемые другими программами, становятся недопустимыми.

Оператор End предоставляет способ заставить программу остановиться. Для нормального прекращения работы программы Visual Basic следует выгрузить все формы. Программа закроется, как только не будет других программ, удерживающих ссылки на объекты, созданные из модулей открытого класса, и не будет выполняться код.

Пример

В этом примере оператор End используется для завершения выполнения кода, если пользователь вводит недопустимый пароль.

См. также

Поддержка и обратная связь

Есть вопросы или отзывы, касающиеся Office VBA или этой статьи? Руководство по другим способам получения поддержки и отправки отзывов см. в статье Поддержка Office VBA и обратная связь.

Источник

Прерывание процедур и функций VBA

Иногда встречаются обстоятельства, при которых нет смысла продолжать выполнение процедуры или функции. VBA имеет операторы Exit и End, которые дают возможность либо завершать процедуру или функцию, либо останавливать всю программу.

Оператор Exit

Для того, чтобы процедура или функция прекратила выполнение, используется одна из двух доступных форм VBA-оператора Exit, в зависимости от того, необходимо ли завершить функцию или процедуру:

Перепишем немного листинг учебной программы, который использовался на позапрошлом уроке:

Здесь содержится код проверки того, была ли выбрана пользователем в окне ввода кнопка «Отмена». Если это так — программа выдает сообщение о том, что не был введен возраст, и прекращает выполнение кода оператором Exit Sub.

Оператор Exit Sub приводит к тому, что VBA немедленно прекращает выполнение кода процедуры. После выполнения этого оператора VBA прекращает выполнение текущей процедуры и возвращается к выполнению той процедуры или функции, которая вызвала процедуру, содержащую оператор Exit Sub.

Оператор End

Для полного завершения выполнения программы используется ключевое слово End в отдельной строке:

При выполнении этого оператора VBA прекращает все выполнение операторов процедуры и функции. Любые имеющиеся переменные перестают существовать и их значения теряются.

Т.к. программа полностью прерывается, необходимо перед оператором End выводить пользователю сообщение о том, что будет происходить и почему. В противном случае пользователи вашей процедуры могут не понять, почему процедура или программа, которую они используют, внезапно прекратила работу. Если программа перестанет выполняться вследствие какого-либо действия пользователя, такого как отмена окна ввода, без объяснения, пользователь процедуры может никогда не узнать, почему процедура заканчивается.

Также не следует забывать закрывать рабочие книги или выполнять другие сервисные работы перед выполнением оператора End, чтобы пользователю программы не приходилось доделывать незаконченные операции.

В начало страницы

В начало страницы

Источник

Оператор Exit (Visual Basic)

Завершает процедуру или блок и немедленно передает управление инструкции после вызова процедуры или определения блока.

Синтаксис

Операторы

Exit Do
Немедленно завершает Do цикл, в котором он отображается. Выполнение продолжается с инструкцией , следующей за оператором Loop . Exit Do может использоваться только внутри Do цикла. При использовании во вложенных Do циклах Exit Do выходит из самого внутреннего цикла и передает управление следующему более высокому уровню вложения.

Exit For
Немедленно завершает For цикл, в котором он отображается. Выполнение продолжается с инструкцией , следующей за оператором Next . Exit For может использоваться только в цикле For . Next или For Each . Next . При использовании во вложенных For циклах Exit For выходит из самого внутреннего цикла и передает управление следующему более высокому уровню вложения.

Exit Function
Немедленно завершает процедуру Function , в которой она отображается. Выполнение продолжается с инструкцией, следующей за оператором, который вызвал процедуру Function . Exit Function может использоваться только внутри Function процедуры.

Чтобы указать возвращаемое значение, можно присвоить его имени функции в строке перед оператором Exit Function . Чтобы назначить возвращаемое значение и выйти из функции в одном операторе, можно использовать оператор Return.

Exit Property
Немедленно завершает процедуру Property , в которой она отображается. Выполнение продолжается инструкцией, которая вызвала процедуру Property , то есть инструкцией, запрашивающей или устанавливающей значение свойства. Exit Property может использоваться только в процедуре Get свойства или Set .

Чтобы указать возвращаемое значение в процедуре Get , можно присвоить значение имени функции в строке перед оператором Exit Property . Чтобы назначить возвращаемое значение и выйти из Get процедуры в одном операторе Return , можно использовать оператор .

Set В процедуре Exit Property оператор эквивалентен оператору Return .

Exit Select
Немедленно выходит из Select Case блока, в котором он отображается. Выполнение продолжается с инструкцией , следующей за оператором End Select . Exit Select может использоваться только внутри Select Case оператора .

Exit Sub
Немедленно завершает процедуру Sub , в которой она отображается. Выполнение продолжается с инструкцией, следующей за оператором, который вызвал процедуру Sub . Exit Sub может использоваться только внутри Sub процедуры.

Sub В процедуре Exit Sub оператор эквивалентен оператору Return .

Exit Try
Немедленно выходит из Try блока или Catch , в котором он отображается. Выполнение продолжается с блоком Finally , если он есть, или с оператором после оператора в End Try противном случае. Exit Try может использоваться только внутри Try блока или Catch , а не внутри Finally блока.

Exit While
Немедленно завершает While цикл, в котором он отображается. Выполнение продолжается с инструкцией , следующей за оператором End While . Exit While может использоваться только внутри While цикла. При использовании во вложенных While циклах передает управление циклу, который является одним вложенным уровнем выше цикла, Exit While где Exit While происходит.

Комментарии

Не путайте Exit операторы с End операторами . Exit не определяет конец оператора .

Пример 1

В следующем примере условие цикла останавливает цикл, если index переменная больше 100. Однако If оператор в цикле приводит к остановке Exit Do цикла, если переменная индекса больше 10.

Пример 2

В следующем примере возвращается значение имени myFunction функции , а затем используется Exit Function для возврата из функции:

Пример 3

В следующем примере оператор Return используется для назначения возвращаемого значения и выхода из функции:

Источник

Оператор Exit

Выполняет выход из блока кода операторов Do…Loop, For…Next, Function, Sub или Property.

Синтаксис

Exit Do
Exit For
Exit Function
Exit Property
Exit Sub

Синтаксис оператора Exit состоит из следующих частей:

Statement Описание
Exit Do Предоставляет способ выхода из . Оператор Loop . Может использоваться только в пределах оператора Do. Loop. Exit Do передает управление оператору, следующему за оператором Loop. При использовании в пределах вложенных операторов Do. Loop, Exit Do передает управление в цикл, находящийся на один вложенный уровень выше, чем цикл, где выполняется оператор Exit Do.
Exit For Предоставляет способ выхода из цикла For. Его можно использовать только в for. Далее или Для каждого. Следующий цикл. Оператор Exit For передает управление оператору, следующему за оператором Next. При использовании во вложенных циклах For оператор Exit For передает управление циклу, находящемуся на один вложенный уровень выше цикла, где выполняется оператор Exit For.
Exit Function Немедленно завершает процедуруFunction, в которой она отображается. Выполнение продолжается с использованием оператора, который следует за оператором, выполнившим вызов процедуры Function.
Exit Property Немедленно завершает процедуру Property , в которой она отображается. Выполнение продолжается с использованием оператора, который следует за оператором, выполнившим вызов процедуры Property.
Exit Sub Немедленно завершает процедуру Sub , в которой она отображается. Выполнение продолжается с использованием оператора, который следует за оператором, выполнившим вызов процедуры Sub.

Замечания

Не следует путать операторы Exit иEnd. Оператор Exit не определяет завершение структуры.

Пример

В этом примере оператор Exit используется для выхода из цикла For. Next, процедур Do. Loop и Sub.

См. также

Поддержка и обратная связь

Есть вопросы или отзывы, касающиеся Office VBA или этой статьи? Руководство по другим способам получения поддержки и отправки отзывов см. в статье Поддержка Office VBA и обратная связь.

Источник

Exit statement

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.

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.

See also

Support and feedback

Have questions or feedback about Office VBA or this documentation? Please see Office VBA support and feedback for guidance about the ways you can receive support and provide feedback.

Источник

vba end

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:
The result of running Exit Sub
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:
Using the VBA End statement to exit macro execution
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 Reset buttonThe 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.

Понравилась статья? Поделить с друзьями:
  • Vba for excel classes
  • Vba for excel class
  • Vba for excel activesheet
  • Vba for excel 2016 pdf
  • Vba for excel 2013