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?
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:
Example usage:
If the function returns an Object type, then you must use the
Set
keyword like this:Example usage:
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:Documentation: http://msdn.microsoft.com/en-us/library/office/gg264233%28v=office.14%29.aspx
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: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:
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:
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:
The below code stores the return value in to the variable
retVal
and thenMsgBox
can be used to display the value:VBA functions treat the function name itself as a sort of variable. So instead of using a "
return
" statement, you would just say: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.