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
Простое значение возвращаемого значения для имени функции все еще не совсем то же, что и оператор Java (или другого) return
, потому что в java, return
завершает функцию, например:
public int test(int x) {
if (x == 1) {
return 1; // exits immediately
}
// still here? return 0 as default.
return 0;
}
В VB эквивалент точный принимает две строки, если вы не устанавливаете возвращаемое значение в конце вашей функции. Итак, в VB точное следствие будет выглядеть так:
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
Так как это так, также приятно знать, что вы можете использовать возвращаемую переменную, как и любую другую переменную в методе. Вот так:
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
Или, крайний пример того, как работает возвращаемая переменная (но не обязательно хороший пример того, как вы должны на самом деле кодировать) — тот, который будет держать вас в ночное время:
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.
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.
The value of 50 would always be returned.
You can also call the GetRange function from a Sub Procedure.
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.
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.
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.
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 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
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
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
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.
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 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.
Select User Defined from the Category List
Select the function you require from the available User Defined Functions (UDF’s).
Alternatively, when you start writing your function in Excel, the function should appear in the drop down list of functions.
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.
Interestingly enough, however, you can still use the function – it just will not appear in the list when looking for it!
If you have declared the second argument as Optional, you can omit it within the Excel sheet as well as within the VBA code.
You can also use the a function that you have created without arguments in your Excel sheet.
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 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.
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
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
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
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
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
Step 7: When we press F8 we can see how this procedure works step by step.
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
Step 2: Similar to above let us declare multiple subroutines with the GoSub statement.
Code:
Sub Example2() GoSub Sample1 GoSub Sample2 End Sub
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
Step 4: Run this code by hitting F5 or Run button.
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
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
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
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
Step 5: Run this code by hitting F5 or Run button placed at the uppermost ribbon of Visual Basic Editor.
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
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 –
- VBA SendKeys (Examples with Excel Template)
- How to Change Name Worksheet in Excel VBA?
- VBA On Error Goto (Examples)
- VBA Input | Excel Templates