Vba excel exit from 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

Содержание

  1. Exit statement
  2. Syntax
  3. Remarks
  4. Example
  5. See also
  6. Support and feedback
  7. Прерывание процедур и функций VBA
  8. Оператор Exit
  9. Оператор End
  10. VBA Exit Sub or Function
  11. Exit a Sub in VBA
  12. Exit a Function in VBA
  13. VBA Coding Made Easy
  14. VBA Code Examples Add-in
  15. Оператор Sub
  16. Синтаксис
  17. Замечания
  18. Пример
  19. См. также
  20. Поддержка и обратная связь

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

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

Оператор Exit

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

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

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

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

Оператор End

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

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

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

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

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

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

Источник

VBA Exit Sub or Function

In VBA, you can exit a Sub or Function, by using the Exit Sub or Exit Function commands.

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:

In the ExitSub, we first enter the For Loop if the value of i is less than 10:

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 the condition is not met, the following statement increases i by 1 and enters in the For loop again:

In the CallExitSub, we first call the Sub ExitSub:

After that we return the Message box:

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 5 th 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:

In the ExitFunc, we first enter the For Loop if the value of i is less than 10:

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 the condition is not met, the following statement increases i by 1 and enters in the For loop again:

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:

After that we return the Message box with the value of 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 5 th 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!

VBA Code Examples Add-in

Easily access all of the code examples found on our site.

Simply navigate to the menu, click, and the code will be inserted directly into your module. .xlam add-in.

Источник

Оператор Sub

Объявляет имя, аргументы и код, формирующий текст процедурыSub.

Синтаксис

[ Частный | Общественного | Друг ] [ Static ] Subname [ ( arglist ) ]
[ операторы ]
[ Exit Sub ]
[ операторы ]
End Sub

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

Part Описание
Public Необязательный параметр. Показывает, что процедура Sub доступна всем другим процедурам во всех модулях. При использовании в модуле, содержащем оператор Option Private, процедура становится недоступной вне проекта.
Private Необязательный параметр. Показывает, что процедура Sub доступна только другим процедурам из модуля, в котором она объявлена.
Friend Необязательный параметр. Используется только в модуле класса. Показывает, что процедура Sub видима по всему проекту, кроме контроллера экземпляра объекта.
Static Необязательный параметр. Показывает, что локальные переменные процедуры Sub сохраняются в промежутках между вызовами. Атрибут Static не влияет на переменные, объявленные вне процедуры Sub, даже если они используются в процедуре.
name Обязательно. Имя процедуры Sub массива; должен соответствовать стандартным правилам именования переменных.
arglist Необязательный параметр. Список переменных, представляющих аргументы, передаваемые в процедуру Sub при ее вызове. В качестве разделителя переменных используется запятая.
Операторы Необязательный параметр. Любая группа операторов, выполняющихся внутри процедуры Sub.

Аргумент arglist имеет следующий синтаксис и элементы:

[ Необязательно ] [ ByVal | ByRef ] [ ParamArray ] varname [ ( ) ] [ Astype ] [ =defaultvalue ]

Part Описание
Необязательное Необязательный параметр. Ключевое слово, которое указывает, что аргумент не является обязательным. Если используется, все последующие аргументы в списке ресурсов также должны быть необязательными и объявляться с помощью ключевого слова Optional . Optional не может использоваться для каких-либо аргументов, если используется ParamArray.
ByVal Необязательный параметр. Указывает, что аргумент передается значением.
ByRef Необязательный параметр. Указывает, что аргумент передается по ссылке. ByRef является значением по умолчанию в Visual Basic.
ParamArray Необязательный параметр. Используется только в качестве последнего аргумента в списке ресурсов , чтобы указать, что окончательный аргумент является необязательныммассивом элементов Variant . Ключевое слово ParamArray позволяет предоставлять произвольное число аргументов. Ключевое слово ParamArray не может использоваться с аргументами ByVal, ByRef или Optional.
варнаме Обязательно. Имя переменной, представляющее аргумент; соответствует стандарту соглашений об именовании переменных.
type Необязательный параметр. Тип данных аргумента, передаваемого процедуре; Может быть byte, Boolean, Integer, Long, Currency, Single, Double, Decimal (в настоящее время не поддерживается), Date, String (только переменная длина), Object, Variant или определенный тип объекта. Если параметр не является Optional, может быть указан определяемый пользователем тип.
Defaultvalue Необязательный параметр. Любая константа или константное выражение. Действительно только для параметров Optional. Если типом является Object, явным значением по умолчанию может быть только Nothing.

Замечания

Если явно не указано с помощью public, private или Friend, процедуры Sub по умолчанию являются общедоступными.

Если static не используется, значение локальных переменных не сохраняется между вызовами.

Ключевое слово Friend может использоваться только в модулях классов. Однако доступ к процедурам Friend может осуществляться в любом модуле проекта. Процедура Friend не отображается в библиотеке типов своего родительского класса; процедура Friend не может быть привязана позднее.

Процедуры Sub могут быть рекурсивными, то есть вызывать сами себя для выполнения определенной задачи. Однако рекурсия может привести к переполнению стека. Как правило, ключевое слово Static не используется с рекурсивными процедурами Sub.

Весь исполняемый код должен находиться в процедурах. Процедуру Sub нельзя объявлять внутри другой процедуры Sub, Function или Property.

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

Как и процедура Function, процедура Sub является отдельной процедурой, которая может принимать аргументы, выполнять последовательность операторов и менять значения своих аргументов. Но в отличие от процедуры Function, которая возвращает значение, процедуру Sub нельзя использовать в выражениях.

Вы вызываете процедуру Sub , используя имя процедуры, за которой следует список аргументов. Дополнительные сведения о вызове процедур Sub см. в инструкции Call.

Переменные, используемые в процедурах Sub, делятся на две категории: объявленные и не объявленные в явном виде внутри процедуры. Переменные, объявленные в явном виде внутри процедуры (с использованием инструкции Dim или ее аналогов) всегда являются локальными для процедуры. Переменные, которые используются, но не были явно объявлены в процедуре, также являются локальными, если они не были объявлены на более высоком уровне вне процедуры.

В процедуре могут использоваться переменные, не объявленные внутри нее в явном виде, однако если на уровне модуля объявлены переменные с такими же именами, может возникнуть конфликт имен. Если процедура ссылается на необъявленную переменную, имя которой совпадает с именем другой процедуры, предполагается, что она ссылается на имя из уровня модуля. Во избежание таких конфликтов рекомендуется объявлять переменные в явном виде. Используйте оператор Option Explicit для принудительного объявления переменных.

Операторы GoSub, GoTo или Return нельзя использовать для входа в процедуру Sub и выхода из нее.

Пример

В приведенном ниже примере оператор Sub используется для определения имени, аргументов и кода, формирующих тело процедуры Sub.

См. также

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

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

Источник

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

Понравилась статья? Поделить с друзьями:
  • Vba excel exit all subs
  • Vba excel evaluate пример
  • Vba excel error codes
  • Vba excel error code
  • Vba excel err raise