Содержание
- Exit statement
- Syntax
- Remarks
- Example
- See also
- Support and feedback
- Оператор Exit (Visual Basic)
- Синтаксис
- Операторы
- Комментарии
- Пример 1
- Пример 2
- Пример 3
- Оператор Exit
- Синтаксис
- Замечания
- Пример
- См. также
- Поддержка и обратная связь
- VBA Break For Loop
- Excel VBA Break For Loop
- How to Break/Exit Loops in VBA?
- #1 – Break For Next Loop
- #2 – Break Do Until Loop
- Recommended Articles
- Excel VBA Tutorial Part 6 — VBA Loops
- The Visual Basic For Loop
- The For . Next Loop
- The For Each Loop
- The Exit For Statement
- The Visual Basic Do While Loop
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.
Источник
Оператор 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 и обратная связь.
Источник
VBA Break For Loop
Excel VBA Break For Loop
VBA Break For Loop is also known as the exit for a loop because every process loop has some instructions or criteria to run several times. But, it is very common that some loops get into an infinite loop, thus corrupting the code. In such scenarios, we need a break or exit from the loop to escape certain situations.
Let us say we have instructed the loop to run 10 times. Based on the condition, if the cell value or any other supplied criteria is successful, it has to exit the Excel loop before completing the full loop quota of 10. This article will show you how to exit the loop based on the criteria.
Table of contents
You are free to use this image on your website, templates, etc., Please provide us with an attribution link How to Provide Attribution? Article Link to be Hyperlinked
For eg:
Source: VBA Break For Loop (wallstreetmojo.com)
How to Break/Exit Loops in VBA?
#1 – Break For Next Loop
Code:
It will insert serial numbers from cell A1 to A10.
It is the obvious thing with For Next Loop.
We want to break the loop when we find any value in the first ten cells. For this, we have entered some text values in cell A8.
We want to instruct this in the code, saying, “if the looping cell has a certain value, it has to exit the loop before the pre-determined limit.”
Code:
Look at these lines of code:
If Cells(K, 1).Value = “” Then
Cells(K, 1).Value = K
Else
Exit For
End If
It says If Cells(K, 1). Value = “looping cell is equal to nothing continue the loop of inserting serial numbers from 1 to 10.
The last part of the loop says:
If the above condition is not TRUE, then the “Exit For” loop.
Now run the code. It will insert serial numbers until the A7 cell.
The above code immediately exited the loop without saying anything; how do we know it has exited the loop.
Code:
When looping through the cell, if it finds any non-empty cell, it will display the message saying, “We got non empty cell, in cell A8. We are exiting the loop”.
It will also inform the user of the loop’s exit with a cell address. We can check the cell address returned in the message box if we enter any value by mistake.
#2 – Break Do Until Loop
Like how we have exited for Next Loop, we can also exit the “Do Until” loop. For example, look at the below code.
Code:
This code also performs the task of inserting serial numbers. For example, if we wish to exit the loop when the variable “k” value becomes 6, we need to enter the criteria as IF k = 6 and then exit the loop.
Code:
It will run the loop until the variable value becomes 6. After that, it will exit the loop. If you wish to show the message to the user, you can add the message box.
Code:
This will show the message below.
Like this, based on the criteria given, we can exit the loop if the criteria are TRUE. Else, we can continue the loop.
Recommended Articles
This article has been a guide to VBA Break For Loop. Here, we learn how to exit/break the VBA loop along with step-by-step examples and a downloadable Excel template. Below are some useful Excel articles related to VBA: –
Источник
Excel VBA Tutorial Part 6 — VBA Loops
If, in your VBA program, you need to perform the same task (i.e. repeat the same piece of code) multiple times, this can be done using one of the VBA Loops.
The VBA Loop types are:
Each of the above loop types is discussed separately below.
The Visual Basic For Loop
The Visual Basic ‘For’ loop takes on two separate forms. These are the For . Next loop and the For Each loop.
The For . Next Loop
The For . Next loop uses a variable, which cycles through a series of values within a specified range. The VBA code inside the loop is then executed for each value. This is best explained by way of a simple example:
For i = 1 To 10
Total = Total + iArray(i)
Next i
The above simple For . Next loop sets the variable i to have the values 1, 2, 3, . 10, and for each of these values, runs through the VBA code inside the loop. Therefore, in the above example, the loop adds each of the members of the array iArray to the variable, Total .
In the above example, no step size is specified, so the loop uses the default step size of 1, when looping from 1 to 10. However, you may sometimes want to step through a loop using different sized steps. This can be done using the Step keyword, as shown in the following simple example.
For d = 0 To 10 Step 0.1
dTotal = dTotal + d
Next d
In the above For loop, because the step size is specified as 0.1, the value of the variable d is set to the values 0.0, 0.1, 0.2, 0.3, . 9.9, 10.0 for each execution of the VBA code inside the loop.
You can also use negative step sizes in the VBA For loop, as is illustrated below:
For i = 10 To 1 Step -1
iArray(i) = i
Next i
In this example, the step size is specified as -1, and so the loop sets the variable i to have the values, 10, 9, 8, . 1.
The For Each Loop
The For Each loop is similar to the For . Next loop but, instead of running through a set of values for a variable, the For Each loop runs through every object within a set of objects. For example, the following code shows the For Each loop used to list every Worksheet in the current Excel Workbook:
For Each wSheet in Worksheets
MsgBox «Found Worksheet: » & wSheet.Name
Next wSheet
The Exit For Statement
If, you want to exit a ‘For’ Loop early, you can use the Exit For statement. This statement causes VBA to jump out of the loop and continue with the next line of code outside of the loop. For example, when searching for a particular value in an array, you could use a loop to check each entry of the array. However, once you have found the value you are looking for, there is no need to continue searching, so you exit the loop early.
The Exit For statement is illustrated in the following example, which loops through 100 array entries, comparing each to the value ‘dVal’. The loop is exited early if dVal is found in the array:
The Visual Basic Do While Loop
The Do While loop repeatedly executes a section of code while a specified condition continues to evaluate to True. This is shown in the following Sub procedure, where a Do While loop is used to print out all values of the Fibonacci Sequence until the current value is greater than 1,000:
Sub Fibonacci()
It can be seen that, in the above example, the condition iFib_Next Do While loop is to place the condition at the end of the loop instead of at the beginning. This causes the loop to be executed at least once, regardless of whether or not the condition initially evaluates to True.
The following code shows the form of a Do While Loop which has the condition at the end of the loop:
Do Until IsEmpty(Cells(iRow, 1))
In the above example, as the condition IsEmpty(Cells(iRow, 1)) is at the start of the Do Until loop, the loop will only be entered if the first cell encountered is non-blank.
However, as illustrated in the Do While loop, you may sometimes want to enter the loop at least once, regardless of the initial condition. In this case, the condition can be placed at the end of the loop, as follows:
Источник
Adblock
detector
Home / VBA / VBA With Statement (With – End With)
Key Points
- Use the VBA With Statement to minimize the code.
- You can use a single object at a time while using the With Statement.
What is VBA With Statement
VBA With is a statement to specify an object for once and then run multiple statements for it. In simple words, by using the “WITH” statement to specify an object, and after that, you can access all the properties and methods in one go. It starts with the “With” and ends with “End With”.
Syntax of VBA With Statement
Following is the syntax that you need to use for using With statement in VBA:
With [OBJECT]
[Statement]
End With
- With: It’s the starting keyword for the statement that tells VBA that you are specifying the object mentioned.
- Object: Here, you need to specify the object that you want to use.
- Statement: A statement(s) that you want to run with the specified object.
- End With: It’s the ending keyword for the statement.
Example to understand the VBA With Statement
Let’s take an example to understand with the statement in depth. Let’s say you want to change, the font color, size, and font name of cell A1. For doing all these three things you need to access three different properties of VBA font and the code would be:
Range("A1").Font.Color = RGB(0, 0, 255)
Range("A1").Font.Size = 16
Range("A1").Font.Name = "Consolas"
But here we going to use the With Statement instead of the above code. To use the VBA With Statement, you can use the following steps:
- First, type the keyboard “With”.
- After that, use the VBA Range to specify the cell A1 with using the font object to specify the font object.
- Next, you need to enter the code for all three properties and the values that you want to apply.
- In the end, use the keyword “End With” to end the statement.
Here’s the code that you have just written.
Sub MyMacro()
With Range("A1").Font
.Color = RGB(0, 0, 255)
.Size = 16
.Name = "Consolas"
End With
End Sub
Now let’s have a look at both codes and try to understand what is the difference that we have got by using the “With” statement.
In the first code, you have used the font object three times and then further used the property that you want to access and want to make changes to it.
But in the second code, you have used the With statement and specified the font object at once. And then three lines of code within the “With” statement to access all three properties.
When you use the “With” statement and specify an object, it tells VBA that all the statements that you have written need to run with the object mentioned. It not only gives you a structured code but also makes a macro run faster and gives it greater efficiency.
Nested With Statement
I told you in the starting that you can only specify a single object to use the With statement. But there is a way to use more than one or even multiple objects with it. That’s by using VBA LOOPS, and we are going to use FOR EACH LOOP to loop through multiple objects and use the “With”.
Let me tell you an example; you need to loop through all the worksheets and do apply all the following things to all the cells in each worksheet.
- Font Size: 16
- Font: Verdena
And in the workbook, you have five worksheets, as I have in the following example:
Use the following steps to write a nested “With” statement.
- First, you need to declare a variable to use a worksheet object.
- After that, as I said, you need to use For Each Loop. So, you need to write a code with the loop that can loop through all the worksheets.
- Now, enter the with statement which can apply font setting that we have discussed above. For referrring to all the cells in the worksheet you can use the “Cells” while specifing the object.
Here’s the full code that you have just written.
Sub MyMacro()
Dim ws As Worksheet
For Each ws In ActiveWorkbook.Worksheets
With Cells
.Font.Size = 16
.Font.Name = "Verdena"
End With
Next ws
End 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”:
As you can see, the ExitSub is exited right after Exit Sub command, so the MsgBox “The value of i is” & i will be never executed.
Exit a Function in VBA
Exiting a function in VBA is similar to exiting a Sub, just the command is Exit Function. In the example, we created the ExitFunc which returns an integer. The Sub CallExitFunction calls this function. Here is the code:
Private Function ExitFunc() As Integer
Dim i As Integer
For i = 1 To 10
If i = 5 Then
ExitFunc = i
Exit Function
End If
Next i
End Function
Private Sub CallExitFunction()
Dim intFunc As Integer
intFunc = ExitFunction()
MsgBox "The value of intFunc is " & intFunc
End Sub
In the ExitFunc, we first enter the For Loop if the value of i is less than 10:
For i = 1 To 10
Next i
After that we check if the value of i is equal to 5, using the If command. If the value is 5, we assign the value of i to the function result and exit the function:
If i = 5 Then
ExitFunc = i
Exit Function
End If
If the condition is not met, the following statement increases i by 1 and enters in the For loop again:
Next i
In the CallExitFunction, we first call the function ExitFunc: To do that we have to declare the variable intFunc type integer and assign the result of the ExitFunc function to it:
Dim intFunc As Integer
intFunc = ExitFunction()
After that we return the Message box with the value of intFunc:
MsgBox "The value of intFunc is " & intFunc
If you run the CallExitFunction, it will first call the function ExitFunc. If you execute this code in the debug mode, you will see that it will go through the loop 5 times. In the 5th iteration, the value of the variable i becomes 5 and the code enters in the If body. Now the value of the ExitFunc becomes i and the function is exited and returned to the CallExitFunction. The next line is MsgBox “The value of intFunc is ” & intFunc:
VBA Coding Made Easy
Stop searching for VBA code online. Learn more about AutoMacro — A VBA Code Builder that allows beginners to code procedures from scratch with minimal coding knowledge and with many time-saving features for all users!
Learn More!
Permalink
Cannot retrieve contributors at this time
title | keywords | f1_keywords | ms.prod | ms.assetid | ms.date | ms.localizationpriority |
---|---|---|---|---|---|---|
Exit statement (VBA) |
vblr6.chm1008916 |
vblr6.chm1008916 |
office |
2a1f4605-8220-c5b1-3760-c710f0535aa8 |
12/03/2018 |
medium |
Exits a block of Do…Loop, For…Next, Function, Sub, or Property code.
Syntax
Exit Do
Exit For
Exit Function
Exit Property
Exit Sub
The Exit statement syntax has these forms:
Statement | Description |
---|---|
Exit Do | Provides a way to exit a Do…Loop statement. It can be used only inside a Do…Loop statement. Exit Do transfers control to the statement following the Loop statement. When used within nested Do…Loop statements, Exit Do transfers control to the loop that is one nested level above the loop where Exit Do occurs. |
Exit For | Provides a way to exit a For loop. It can be used only in a For…Next or For Each…Next loop. Exit For transfers control to the statement following the Next statement. When used within nested For loops, Exit For transfers control to the loop that is one nested level above the loop where Exit For occurs. |
Exit Function | Immediately exits the Function procedure in which it appears. Execution continues with the statement following the statement that called the Function. |
Exit Property | Immediately exits the Property procedure in which it appears. Execution continues with the statement following the statement that called the Property procedure. |
Exit Sub | Immediately exits the Sub procedure in which it appears. Execution continues with the statement following the statement that called the Sub procedure. |
Remarks
Do not confuse Exit statements with End statements. Exit does not define the end of a structure.
Example
This example uses the Exit statement to exit a For…Next loop, a Do…Loop, and a Sub procedure.
Sub ExitStatementDemo() Dim I, MyNum Do ' Set up infinite loop. For I = 1 To 1000 ' Loop 1000 times. MyNum = Int(Rnd * 1000) ' Generate random numbers. Select Case MyNum ' Evaluate random number. Case 7: Exit For ' If 7, exit For...Next. Case 29: Exit Do ' If 29, exit Do...Loop. Case 54: Exit Sub ' If 54, exit Sub procedure. End Select Next I Loop End Sub
See also
- Data types
- Statements
[!includeSupport and feedback]
To start with, make sure you have a good understanding of what a function is and how it works. You can get a great overview in my articles here:
What is “You’ve Entered too Many Arguments”?
How Do You Fix “Compile Error: Argument not optional”?
How do you stop a function from executing fully?
There may be situations in which we need to stop executing a function and to immediately return to the point of function call without executing the rest of the code in the function. This is where the statement “Exit Function” comes into the picture. This statement serves that purpose without causing any compile or runtime errors.
Sample Scenarios
Let us consider the following examples one-by-one.
Example 1
A function is developed to check if a particular person’s name exists in a list of 1000 members. The list is available on a webpage and there is no provision to directly find the existence of that name in the list.
We’ll use a loop to compare the person’s name against each of the names in the list. Once we find that it’s in the 400th position on the list, there is no need to continue with the comparison against the other items. That would be a mere waste of time.
In general, we’d use the “Exit for” statement here to skip the rest of the iterations in the loop. This “Exit For” statement takes the program control to the line after the respective “Next” statement of the “For” loop. But using “Exit Function” statement skips all the statements in the function and takes us back to the function call.
Sub Exit_Function_demo() 'Calling function / function call Call findme("Wales") 'Just a statement that prints after the function call Debug.Print "Post function call" End Sub Function findme(full_name) ' A for loop to iterate through all the items in the sheet in col 1 For i = 1 To 10 ' inside loop 'Store the cell valur in a variable and print it. new_value = Cells(i, 1).Value Debug.Print new_value 'Compare the paramter passed with the cell value to check condition If new_value = full_name Then 'Print if found Debug.Print "The name " & full_name &" exists in the list in the row number " & i 'Exit the function Exit Function End If Next 'This will execute only if the value passed in te parameter is not in the list. Debug.Print "Outside Loop" End Function
Example 2
Let’s imagine a function that calculates maturity amount and interest for fixed deposits based on the age and gender of our customers. For the sake of this example, we are collecting age and gender to define the interest rate. The logic uses this criteria:
- Males above or equal to 60 yrs = Senior Citizens
- Females above or equal to 58 yrs = Senior Citizens
- Rate of Interest for Senior Citizens = 9%
- Rate of Interest for non-Senior Citizens = 6%
This way, since we get the age first, if it is greater than or equal to 60, we can completely bypass getting gender as an input. The “Exit Function” statement is of use here.
Sub calc_mat_amt() 'Declare variables Dim p, n, roi 'Initialize variable values. Receive input for customer's age and gender p = 10000 n = 1 gender = InputBox("Input gender of the customer") age = InputBox("Input age of the customer") 'Call the function to find roi roi = find_roi(gender, age) 'calculate the maturity amount matamt = p + ((p * n * r) / 100) End Sub Function find_roi(gender, age) 'first condition is common to males and females If age > 59 Then find_roi = 9 Debug.Print "Part 1 executed" Exit Function Else ' condition to filter out the females who are senior citizens If gender = "Female" And age > 57 Then find_roi = 9 Debug.Print "Part 2 executed" Exit Function Else ' all other non- senior citizens find_roi = 6 Debug.Print "Part 3 executed" Exit Function End If End If ' Once the function is exited, the blow line would not be printed. Debug.Print "this part of the function is skipped" End Function
Example 3
Now let us see a different example. Assume that the end user who is going to run this procedure wants to check his horoscope.
Sub astro() 'function call Call check_my_horoscope 'Print a statement after function call Debug.Print "Function call is executed" End Sub Function check_my_horoscope() Dim belief, dob 'Find the interest of the user belief = MsgBox("Do you believe in astrology?", vbYesNo) 'Do not allow user to proceed further if he has no interest. 'Value for vbNo is 7 If belief = 7 Then Debug.Print ("This module is not for you") Exit Function End If 'Get the date of birth of the user dob = InputBox("Enter your date of birth") 'Do not allow the user to proceed further if the user enters and invalid dob. If IsDate(dob) = False Then Debug.Print ("Invalid Dob. Exiting module. Try again later") Exit Function End If 'Rest of the horoscope checking code Debug.Print "Rest of the code goes here. " End Function
Output for the above code with input values “Yes” and “45”
Output of the same code with “No” as the first input ( for that message box).
Example 4
Here is another piece of code that displays a food menu for each day of the week. Run the code with different inputs to understand how it works.
Sub hotel() 'code to call the function Call food_menu End Sub Function food_menu() 'receive the input from the user strWeekday = InputBox("Enter the day") 'menu items for each day . We exit only if it is a holiday or an invalid day If LCase(strWeekday) = "sunday" Then Debug.Print "The Restaurant is closed on Sundays !" Exit Function ElseIf LCase(strWeekday) = "monday" Then Debug.Print "Tomato Rice is available at 3$" ElseIf LCase(strWeekday) = "tuesday" Then Debug.Print "Chappatis are available at 1$ each" ElseIf LCase(strWeekday) = "wednesday" Then Debug.Print "Lemon Rice is available at 3$" ElseIf LCase(strWeekday) = "thursday" Then Debug.Print "Idlies are available at 1$ each" ElseIf LCase(strWeekday) = "friday" Then Debug.Print "Noodles is available at 1$" ElseIf LCase(strWeekday) = "saturday" Then Debug.Print "Burger is available at 2$" Else Debug.Print "The day entered is invalid" Exit Function End If 'validate the purchase purchase = MsgBox("Do you wish to buy?", vbYesNo) 'end the module if user doesn't want to buy If purchase = 7 Then Debug.Print "Thank you for the enquiry. You will exit the module now" Exit Function End If 'generate a token and greet the user if he is interested to buy. 'code to generate a token Debug.Print "Collect your token.Pay at the counter. Bon appétit " End Function
Conclusion
VBA offers numerous methods to manage the movement of runtime control in our code. For example:
- Loops like For, foreach, do until, while
- Statements like “Exit for”, “Exit do”
- If conditions with a variety of structures like simple if, else if, nested if
However, there might be situations where you need to stop or restrict the flow of execution in a specific direction without using any of these features. That’s where “Exit Function” statement comes to the rescue and simplifies our code.
See also:
Else Do Nothing