How do I return a result from a function?
For example:
Public Function test() As Integer
return 1
End Function
This gives a compile error.
How do I make this function return an integer?
For non-object return types, you have to assign the value to the name of your function, like this:
Public Function test() As Integer
test = 1
End Function
Example usage:
Dim i As Integer
i = test()
If the function returns an Object type, then you must use the Set keyword like this:
Public Function testRange() As Range
Set testRange = Range("A1")
End Function
Example usage:
Dim r As Range
Set r = testRange()
Note that assigning a return value to the function name does not terminate the execution of your function. If you want to exit the function, then you need to explicitly say Exit Function. For example:
Function test(ByVal justReturnOne As Boolean) As Integer
If justReturnOne Then
test = 1
Exit Function
End If
'more code...
test = 2
End Function
Documentation: Function Statement
VBA functions treat the function name itself as a sort of variable. So instead of using a "return" statement, you would just say:
test = 1
Notice, though, that this does not break out of the function. Any code after this statement will also be executed. Thus, you can have many assignment statements that assign different values to test, and whatever the value is when you reach the end of the function will be the value returned.
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
Related
How do I return a result from a function?
For example:
Public Function test() As Integer
return 1
End Function
This gives a compile error.
How do I make this function return an integer?
For non-object return types, you have to assign the value to the name of your function, like this:
Public Function test() As Integer
test = 1
End Function
Example usage:
Dim i As Integer
i = test()
If the function returns an Object type, then you must use the Set keyword like this:
Public Function testRange() As Range
Set testRange = Range("A1")
End Function
Example usage:
Dim r As Range
Set r = testRange()
Note that assigning a return value to the function name does not terminate the execution of your function. If you want to exit the function, then you need to explicitly say Exit Function. For example:
Function test(ByVal justReturnOne As Boolean) As Integer
If justReturnOne Then
test = 1
Exit Function
End If
'more code...
test = 2
End Function
Documentation: Function Statement
VBA functions treat the function name itself as a sort of variable. So instead of using a "return" statement, you would just say:
test = 1
Notice, though, that this does not break out of the function. Any code after this statement will also be executed. Thus, you can have many assignment statements that assign different values to test, and whatever the value is when you reach the end of the function will be the value returned.
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
Function jaineqtn(Rcoeff As Single)
Dim F_old As Single
F_old = 1.325 / (WorksheetFunction.Ln(Rcoeff / 3.7)) ^ 2
End Function
Sub Macro1()
Dim val As Single
val = jaineqtn(5)
MsgBox val
End Sub
why does my function return 0 in a sub in VBA
Because your Function returns Empty:
Function jaineqtn(Rcoeff As Single)
Dim F_old As Single
F_old = 1.325 / (WorksheetFunction.Ln(Rcoeff / 3.7)) ^ 2
End Function
You declare a local variable F_old, but you never set a return value. Thus, your function, having an implicit return value type of Variant, will return Variant's default value, which is Empty.
Then, in your Sub Macro1, you assign that default return value to a variable of type Single. Assigning Empty to a Single yields 0.
Maybe you meant to write the following?
Function jaineqtn(Rcoeff As Single) As Single
jaineqtn = 1.325 / (WorksheetFunction.Ln(Rcoeff / 3.7)) ^ 2
End Function
I have a vba function that checks if a user-input from a text box is positive integer or not. The code below:
Public Function IsPosInteger(n As Variant) As Boolean
If IsNumeric(n) = True Then
If (n = Int(n)) And n > 0 Then
IsPosInteger = True
Else
IsPosInteger = False
End If
Else
IsPosInteger = False
End If
End Function
The problem is that upon testing the function still returns false for a valid positive integer. Upon further investigation, I noticed that the variable type by default for texbox values is String. Probably the main reason why IsNumeric is returning false.
Function below is what I used to determine the type of the variable.
TypeName(n)
This worked for me.
I used an inputbox that contained:
strings (False)
negative numbers (False)
positive numbers (true)
positive numbers and letters (false)
Public Function IsPosInteger(n As Variant) As Boolean
If n > 0 And IsNumeric(n) Then IsPosInteger = True
End Function
Now, the other issue may arise that the value n is still technically type String due to the nature of the inputbox -- even if it passes the test of this function. If you wish to change this behavior, continue reading.
To do this, ensure that you are using ByRef (when this is intentional, I usually type out ByRef on the argument, even though it is automatically assumed by VBA that any argument passed to a function is ByRef if it doesn't explicitly state ByVal).
If this is the outcome you are wanting, then you can use this function:
Public Function IsPosInteger(ByRef n As Variant) As Boolean
If n > 0 And IsNumeric(n) Then
IsPosInteger = True
n = clng(n) '<-- This converts the variant (currently a string) n to type long,
' only if it passes the test
end if
End Function
You must ensure that n in the calling routine is of type Variant, else you will encounter an error.
Public Function IsPosInteger(s As String) As Boolean 'boolean data type is false by default.
If (IsNumeric(s) = False) Then Exit Function
If (s < 1) Then Exit Function
If (InStr(s, ".") = False) Then IsPosInteger = True
End Function
Function tests that the input is numeric, not less than 1, and does not contain a decimal. Here is an example of how you could use it in your calling sub:
Sub TestInput()
Dim sUserInput As String
Dim boolPositiveInt As Boolean
Dim i As Integer
sUserInput = Range("A1").Value2
boolPositiveInt = IsPosInteger(sUserInput)
If (boolPositiveInt = False) Then
MsgBox "Invalid input. Please enter a positive integer"
Exit Sub
End If
i = CInt(sUserInput)
'continue working with integer variable here
End Sub
How do I return a result from a function?
For example:
Public Function test() As Integer
return 1
End Function
This gives a compile error.
How do I make this function return an integer?
For non-object return types, you have to assign the value to the name of your function, like this:
Public Function test() As Integer
test = 1
End Function
Example usage:
Dim i As Integer
i = test()
If the function returns an Object type, then you must use the Set keyword like this:
Public Function testRange() As Range
Set testRange = Range("A1")
End Function
Example usage:
Dim r As Range
Set r = testRange()
Note that assigning a return value to the function name does not terminate the execution of your function. If you want to exit the function, then you need to explicitly say Exit Function. For example:
Function test(ByVal justReturnOne As Boolean) As Integer
If justReturnOne Then
test = 1
Exit Function
End If
'more code...
test = 2
End Function
Documentation: Function Statement
VBA functions treat the function name itself as a sort of variable. So instead of using a "return" statement, you would just say:
test = 1
Notice, though, that this does not break out of the function. Any code after this statement will also be executed. Thus, you can have many assignment statements that assign different values to test, and whatever the value is when you reach the end of the function will be the value returned.
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
I want to create two functions: one should "produce" a number and the other should perform a function with as parameter this number.
I got the following code
sub get_number()
Dim x as Integer
x = 3
return x
end sub
But I cant get this to return a numeric value because it throws a compile error. Any thoughts on how I can get this function to return a x value and store it in a new variable (fe y()
You need to use a function, not a Sub, and assign the return value to the name of the function:
Function get_number()
Dim x as Integer
x = 3
get_number = x
end Function
then use:
y = get_number
in your other code.
Sub can't return a value; use a Function:
Function get_number()
Dim x as Integer
x = 3
get_number = x
End Function
myNumber = get_number()
MsgBox myNumber ' will return the 3
Or you can stick with the Sub and handle the return value with a parameter (which you'll have to define in the calling function or earlier)
Sub get_number(byRef myNumber) ' accepts myNumber as a parameter and returns its value
Dim x as Integer
x = 3
myNumber = x
End Sub