Vba excel return from function

Just setting the return value to the function name is still not exactly the same as the Java (or other) return statement, because in java, return exits the function, like this:

public int test(int x) {
    if (x == 1) {
        return 1; // exits immediately
    }

    // still here? return 0 as default.
    return 0;
}

In VB, the exact equivalent takes two lines if you are not setting the return value at the end of your function. So, in VB the exact corollary would look like this:

Public Function test(ByVal x As Integer) As Integer
    If x = 1 Then
        test = 1 ' does not exit immediately. You must manually terminate...
        Exit Function ' to exit
    End If

    ' Still here? return 0 as default.
    test = 0
    ' no need for an Exit Function because we're about to exit anyway.
End Function 

Since this is the case, it’s also nice to know that you can use the return variable like any other variable in the method. Like this:

Public Function test(ByVal x As Integer) As Integer

    test = x ' <-- set the return value

    If test <> 1 Then ' Test the currently set return value
        test = 0 ' Reset the return value to a *new* value
    End If

End Function 

Or, the extreme example of how the return variable works (but not necessarily a good example of how you should actually code)—the one that will keep you up at night:

Public Function test(ByVal x As Integer) As Integer

    test = x ' <-- set the return value

    If test > 0 Then

        ' RECURSIVE CALL...WITH THE RETURN VALUE AS AN ARGUMENT,
        ' AND THE RESULT RESETTING THE RETURN VALUE.
        test = test(test - 1)

    End If

End Function

In this Article

  • Creating a Function without Arguments
  • Calling a Function from a Sub Procedure
  • Creating Functions
    • Single Argument
    • Multiple Arguments
    • Optional Arguments
    • Default Argument Value
    • ByVal and ByRef
  • Exit Function
  • Using a Function from within an Excel Sheet

This tutorial will teach you to create and use functions with and without parameters in VBA

VBA contains a large amount of built-in functions for you to use, but you are also able to write your own.   When you write code in VBA, you can write it in a Sub Procedure, or a Function Procedure. A Function Procedure is able to return a value to your code.  This is extremely useful if you want VBA to perform a task to return a result. VBA functions can also be called from inside Excel, just like Excel’s built-in Excel functions.

Creating a Function without Arguments

To create a function you need to define the function by giving the function a name. The function can then be defined as a data type indicating the type of data you want the function to return.

You may want to create a function that returns a static value each time it is called – a bit like a constant.

Function GetValue() As Integer
   GetValue = 50
End Function

If you were to run the function, the function would always return the value of 50.

vba function no argument

You can also create functions that refer to objects in VBA but you need to use the Set Keyword to return the value from the function.

Function GetRange() as Range
  Set GetRange = Range("A1:G4")
End Function

If you were to use the above function in your VBA code, the function would always return the range of cells A1 to G4 in whichever sheet you are working in.

Calling a Function from a Sub Procedure

Once you create a function, you can call it from anywhere else in your code by using a Sub Procedure to call the function.

vba function no argument 1

The value of 50 would always be returned.

You can also call the GetRange function from a Sub Procedure.

vba function no argument range

In the above example, the GetRange Function is called by the Sub Procedure to bold the cells in the range object.

Creating Functions

Single Argument

You can also assign a parameter or parameters to your function.  These parameters can be referred to as Arguments.

Function ConvertKilosToPounds (dblKilo as Double) as Double
   ConvertKiloToPounds = dblKilo*2.2
End Function

We can then call the above function from a Sub Procedure in order to work out how many pounds a specific amount of kilos are.

vba function return value

A function can be a called from multiple procedures within your VBA code if required.  This is very useful in that it stops you from having to write the same code over and over again.  It also enables you to divide long procedures into small manageable functions.

vba functions return values 1

In the above example, we have 2 procedures – each of them are using the Function to calculate the pound value of the kilos passed to them in the dblKilo Argument of the function.

Multiple Arguments

You can create a Function with multiple arguments and pass the values to the Function by way of a Sub Procedure.

Function CalculateDayDiff(Date1 as Date, Date2 as Date) as Double
   CalculateDayDiff = Date2-Date1
End Function

We can then call the function to calculate the amount of days between 2 dates.

vba-function-2-arguments

Optional Arguments

You can also pass Optional arguments to a Function.  In other words, sometimes you may need the argument, and sometimes you may not – depending on what code you are using the Function with .

Function CalculateDayDiff(Date1 as Date, Optional Date2 as Date) as Double
'check for second date and if not there, make Date2 equal to today's date.
   If Date2=0 then Date2 = Date
'calculate difference
   CalculateDayDiff = Date2-Date1 
End Function

vba function optional parameter

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!

automacro

Learn More

Default Argument Value

You can also set the default value of the Optional arguments when you are creating the function so that if the user omits the argument, the value that you have put as default will be used instead.

Function CalculateDayDiff(Date1 as Date, Optional Date2 as Date="06/02/2020") as Double 
'calculate difference 
   CalculateDayDiff = Date2-Date1 
End Function

vba functions optional default

ByVal and ByRef

When you pass values to a function, you can use the ByVal or ByRef keywords.  If you omit either of these, the ByRef is used as the default.

ByVal means that you are passing a copy of the variable to the function, whereas ByRef means you are referring to the original value of the variable.  When you pass a  copy of the variable (ByVal), the original value of the variable is NOT changed, but when you reference the variable, the original value of the variable is changed by the function.

Function GetValue(ByRef intA As Integer) As Integer
   intA = intA * 4
   GetValue = intA
End Function

In the function above, the ByRef could be omitted and the function would work the same way.

Function GetValue(intA As Integer) As Integer
   intA = intA * 4
   GetValue = intA
End Function

To call this function, we can run a sub-procedure.

Sub TestValues()
   Dim intVal As Integer
'populate the variable with the value 10
   intVal = 10
'run the GetValue function, and show the value in the immediate window
   Debug.Print GetValue(intVal)
'show the value of the intVal variable in the immediate window 
   Debug.Print  intVal
End Sub

vba function by ref

Note that the debug windows show the value 40 both times.  When you pass the variable IntVal to the function – the value of 10 is passed to the function, and multiplied by 4.  Using the ByRef keyword (or omitting it altogether), will AMEND the value of the IntVal variable.   This is shown when you show first the result of the function in the immediate window (40), and then the value of the IntVal variable in the debug window (also 40).

If we do NOT want to change the value of the original variable, we have to use ByVal in the function.

Function GetValue(ByVal intA As Integer) As Integer
intA = intA * 4
GetValue = intA
End Function

Now if we call the function from a sub-procedure, the value of the variable IntVal will remain at 10.

vba function byval

Exit Function

If you create a function that tests for a certain condition, and once the condition is found to be true, you want return the value from the function, you may need to add an Exit Function statement in your Function in order to exit the function before you have run through all the code in that function.

Function FindNumber(strSearch As String) As Integer
   Dim i As Integer
'loop through each letter in the string
   For i = 1 To Len(strSearch)
   'if the letter is numeric, return the value to the function
      If IsNumeric(Mid(strSearch, i, 1)) Then
         FindNumber= Mid(strSearch, i, 1)
   'then exit the function
         Exit Function
      End If
   Next
   FindNumber= 0
End Function

The function above will loop through the string that is provided until it finds a number, and then return that number from the string.  It will only find the first number in the string as it will then Exit the function.

The function above can be called by a Sub routine such as the one below.

Sub CheckForNumber()
   Dim NumIs as Integer
'pass a text string to the find number function
   NumIs = FindNumber("Upper Floor, 8 Oak Lane, Texas")
'show the result in the immediate window
   Debug.Print NumIs
End Sub

vba function exit function

VBA Programming | Code Generator does work for you!

Using a Function from within an Excel Sheet

In addition to calling a function from your VBA code using a sub procedure, you can also call the function from within your Excel sheet.  The functions that you have created should by default appear in your function list in the User Defined section of the function list.

Click on the fx to show the Insert Function dialog box.

vba function fx

Select User Defined from the Category List

vba function udf

Select the function you require from the available User Defined Functions (UDF’s).

vba function excel sheet

Alternatively, when you start writing your function in Excel, the function should appear in the drop down list of functions.

vba function dropdown

If you do not want the function to be available inside an Excel sheet, you need to put the Private word in front of the word Function when you create the function in your VBA code.

Private Function CalculateDayDiff(Date1 as Date, Date2 as Date) as Double 
   CalculateDayDiff = Date2-Date1 
End Function

It will now not appear in the drop down list showing the Excel functions available.

vba function dropdown 2

Interestingly enough, however, you can still use the function – it just will not appear in the list when looking for it!

vba function excel

If you have declared the second argument as Optional, you can omit it within the Excel sheet as well as within the VBA code.

vba function excel 2

You can also use the a function that you have created without arguments in your Excel sheet.

vba function no argument excel

As You may know, in general in programming to return a result from function there is Return statement. Even Visual Basic has it. Unfortunately there is no such thing in VBA. In this article I’m going to show You how to return a result from VBA function.

Let’s start with function

For the purpose of this article I’ve created functionModulo, which is very similar to the Mod function.

Function functionModulo(x As Integer, y As Integer) As Boolean

Dim divisionRest As Double, divisionRestStatus As Integer
Let divisionRest = x / y - Fix(x / y)

If divisionRest > 0 Then
    divisionRestStatus = 0
Else
    divisionRestStatus = 1
End If

If divisionRestStatus = 1 Then
    functionModulo = True
Else
    functionModulo = False
End If

End Function

This function allows You to check if there is a divisibility between two numbers. If there is a rest from division the function returns False, if there is no any – function returns True.

So to describe the work of this function, I was using return word. But not as a statement in code. To return the result in VBA function You need to use the function name itself and put it a value.

functionModulo = True

Unfortunately the function not stops there and exits. It just go further.

As close as possible

I decided to modify this function to make it as similar to Return statement schema as possible.

So first of all I cut it a little bit.

Function functionModulo(x As Integer, y As Integer) As Boolean

Dim divisionRest As Double
Let divisionRest = x / y - Fix(x / y)

If divisionRest > 0 Then
    functionModulo = False
Else
    functionModulo = True
End If

End Function

Then I wanted to have the same effect after returning the result from function as Return statement brings.

Function functionModulo(x As Integer, y As Integer) As Boolean

Dim divisionRest As Double
Let divisionRest = x / y - Fix(x / y)

If divisionRest > 0 Then functionModulo = False: Exit Function
If divisionRest = 0 Then functionModulo = True

End Function

That’s why after returning the value I added Exit Function.

If divisionRest > 0 Then functionModulo = False: Exit Function

I was almost done, but also figured out that we can only check for valid values. This means that I could set False value at the beginning as default. One conditional less in code. Cleaner the code.

Function functionModulo(x As Integer, y As Integer) As Boolean

functionModulo = False

Dim divisionRest As Double: Let divisionRest = x / y - Fix(x / y)

If divisionRest = 0 Then functionModulo = True

End Function

Having nothing after the conditional for True value I decided to erase Exit Function statement. In this case it is not needed, but in general it is really good approach to simulate Return statement as from other programming languages.

To sum up

To avoid unnecessary conditionals put the default value at the beginning of the function. You can also do that in the end of the code, only if You simulate the Return statement in VBA – pass the result in the function name and Exit Function just right after that line.

I’m very advanced in VBA, Excel, also easily linking VBA with other Office applications (e.g. PowerPoint) and external applications (e.g. SAP). I take part also in RPA processes (WebQuery, DataCache, IBM Access Client Solutions) where I can also use my SQL basic skillset. I’m trying now to widen my knowledge into TypeScript/JavaScript direction.
View all posts by Tomasz Płociński

VBA Return

VBA Return Statement

In this article, we will see an outline on Excel VBA Return. It is a statement in VBA which is used for the user-defined functions with the GoSub statement. This statement can also be used outside of a subprocedure when we are using a user-defined function. And when we are using the GoSub statement with the return statement then both GoSub and return statements should be in the same procedure. Now let us discuss what the difference between these two procedures is. First, we will begin with the GoSub statement. In this statement, we stay in the same procedure but move to another statement and get a result with some lines execution of code and then return to the original procedure.

The next is the use of the return statement in a user-defined function. In the user-defined function, a function is created which is returns a value through return statement. We will discuss both types of use of the return statement through some examples.

How to Use Go Sub Return Statement in VBA?

We will learn how to use Go Sub Return Statement in Excel by using the VBA Code.

You can download this VBA Return Excel Template here – VBA Return Excel Template

Example #1 – VBA Return Statement

Let us first discuss how Return with GoSub Statement works in VBA. How do we execute them and what we will learn in this example?. For this, follow the below steps:

Step 1: Insert a new module inside Visual Basic Editor (VBE). Click on Insert tab > select Module.

Insert Module

Step 2: Once we have a module in the Editor now let us begin with the procedure of declaring a sub-function.

Code:

Sub Example1()

End Sub

VBA Return Example 1-1

Step 3: Now let us send the execution to another line by the GoSub Statement but within the same procedure.

Code:

Sub Example1()

GoSub Sample

End Sub

VBA Return Example 1-2

Step 4: Now let us exit the subprocedure, for now, let us keep this in mind exit sub and end sub are two different.

Code:

Sub Example1()

GoSub Sample
Exit Sub

End Sub

Exit Sub Example 1-3

Step 5: Now we can perform some execution of lines of code for the subroutine.

Code:

Sub Example1()

GoSub Sample
Exit Sub
Sample:
MsgBox "This is a sample document"

End Sub

VBA Return Example 1-4

Step 6: Now we will use the return statement to move back to the original procedure.

Code:

Sub Example1()

GoSub Sample
Exit Sub
Sample:
MsgBox "This is a sample document"
Return

End Sub

VBA Return Example 1-5

Step 7: When we press F8 we can see how this procedure works step by step.

VBA Return Example Output 1

Now we can see in the steps that process moved to the line of Sample subroutine when the compiler was on the Gosub Statement and it again moved back to exit sub after giving us the result to Exit substatement.

Example #2 – VBA Return Statement

In the above example, we use a single subroutine and what happens if there are multiple subroutines with multiple GoSub and multiple Return statements. Let us find out in example 2. For this, follow the below steps:

Step 1: We will proceed with the same module just with another subprocedure.

Code:

Sub Example2()

End Sub

VBA Return Example 2-1

Step 2: Similar to above let us declare multiple subroutines with the GoSub statement.

Code:

Sub Example2()

GoSub Sample1
GoSub Sample2

End Sub

Multiple Subroutines Example 2-2

Step 3: Now let us exit the sub and define what those subroutines will do.

Code:

Sub Example2()

GoSub Sample1
GoSub Sample2
Exit Sub
Sample1:
MsgBox "This is first Execution"
Return
Sample2:
MsgBox "This is second Execution"
Return

End Sub

VBA Return Example 2-3

Step 4: Run this code by hitting F5 or Run button.

VBA Return Example Output 2

In this example, Code worked in the same way, the compiler went to GoSub Sample1 and executed the lines of code for sample1 then it returned it to GoSub Sample2 and then again went to execute the lines of code for sample2 and then the return statement took it back to the exit substatement.

Example #3 – VBA Return Statement

Let us use a somewhat realistic example for the GoSub statement such as for addition. For this, follow the below steps:

Step 1: Declare a subprocedure for example 3.

Code:

Sub Example3()

End Sub

VBA Return Example 3-1

Step 2: Define two integer variables and ask the user to provide input as integers.

Code:

Sub Example3()

Dim i As Integer, b As Integer
i = InputBox("Enter first number")
b = InputBox("Enter second number")

End Sub

Integer Variables Example 3-2

Step 3: Now let us use the GoSub statement and perform the addition operation as follows.

Code:

Sub Example3()

Dim i As Integer, b As Integer
i = InputBox("Enter first number")
b = InputBox("Enter second number")
GoSub Addition
MsgBox "Execution Complete"
Exit Sub
Addition:
MsgBox i + b

End Sub

Addition Operation Example 3-3

Step 4: Now we can use the return statement to go back and inform that execution is complete.

Code:

Sub Example3()

Dim i As Integer, b As Integer
i = InputBox("Enter first number")
b = InputBox("Enter second number")
GoSub Addition
MsgBox "Execution Complete"
Exit Sub
Addition:
MsgBox i + b
Return

End Sub

Return Statement Example 3-4

Step 5: Run this code by hitting F5 or Run button placed at the uppermost ribbon of Visual Basic Editor.

VBA Return Example Output 3

Example #4 – VBA Return Statement

For this example look at the below example of code as follows.

Code:

Sub Example4()
Dim i As Integer, k As Integer, area1 As Integer
i = 2
k = 3
area1 = area(i, k)
MsgBox area1
End Sub
Public Function area(x As Integer, y As Integer) As Integer
area = x * y
End Function

VBA Return Example 4-1

In this code, there is no return statement used but it still returns the function with a value.

Explanation of VBA Return

  • We have seen why we use the return statement,  in both of the cases with the use of GoSub statement and User-defined functions. However, there is a slight difference. In the GoSub function, we used a Return statement so that the compiler can return to the next code after the subroutine, and in user-defined functions return statement returned the value to be generated by the function.
  • We have seen two different methods of using the Return statement through the examples above.

Method 1: The first method is the use of GoSub statement with the return statement.

Method 2: The second method is to use return values in a user-defined function.

Things to Remember

There are few things that we need to remember about the Return statement in VBA and they are as follows:

  • The return statement is placed where the execution of codes for the procedures is completed.
  • For the GoSub statement, the GoSub and return statement should be in the same procedure.
  • For User-defined functions, the values are returned using the function name.
  • There can be more than one return statement in the same procedure.

Recommended Articles

This is a guide to the VBA Return. Here we discuss how to Use Go Sub Return Statement in Excel VBA along with practical examples and a downloadable excel template. You can also go through our other suggested articles –

  1. VBA SendKeys (Examples with Excel Template)
  2. How to Change Name Worksheet in Excel VBA?
  3. VBA On Error Goto (Examples)
  4. VBA Input | Excel Templates


To return a value from a function in VBA, you must assign the value to the function name.

For example, we can create the following function to divide two values and then return the result of the division:

Function DivideValues(x, y)
    DivideValues = x / y
End Function

The name of this function is DivideValues, so to return a value from this function we must assign the result of x / y to a variable with the same name of DivideValues.

If your function involves If Else logic, you can assign the value to the function name multiple times.

For example, you can create the following function that returns “Cannot divide by zero” if you attempt to divide by zero or else simply return the result of the division:

Function DivideValues(x, y)
    If y = 0 Then
      DivideValues = "Cannot divide by zero"
    Else
      DivideValues = x / y
    End If
End Function

The following example shows how to use this syntax in practice.

Suppose we would like to create a function in VBA to divide the value in cell A2 by the value in cell B2:

We can create the following function to do so:

Function DivideValues(x, y)
    DivideValues = x / y
End Function

When we run this macro, we receive the following output:

The function returns a value of 5, which is the result of 50 divided by 10.

We could also create a function that uses If Else logic to first check if the value that we’re dividing by is not equal to zero:

Function DivideValues(x, y)
    If y = 0 Then
      DivideValues = "Cannot divide by zero"
    Else
      DivideValues = x / y
    End If
End Function

If we change the value in cell B2 and then use this function to perform division, we’ll receive the following output:

Since we attempted to divide by zero, “Cannot divide by zero” is returned by the function.

Additional Resources

The following tutorials explain how to perform other common tasks in VBA:

How to Comment a Block of Code in VBA
How to Check if File Exists Using VBA
How to Create Folders Using VBA

Like this post? Please share to your friends:
  • Vba excel spinbutton пример
  • Vba excel replace пример
  • Vba excel sort key1
  • Vba excel replace in string
  • Vba excel soap запрос