Using Exit Function in VBA - VBA and VB.Net Tutorials, Education and Programming Services

Using Exit Function in VBA

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

Function is skipped because person is not a senior citizen

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"

Code output for exiting module

Output of the same code with “No" as the first input ( for that message box).

Function call is executed

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

Leave a Reply

Your email address will not be published. Required fields are marked *