Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to return a result from a VBA function

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?

like image 678
Mike Avatar asked May 06 '10 14:05

Mike


People also ask

How do you return a value from a function?

To return a value from a function, you must include a return statement, followed by the value to be returned, before the function's end statement. If you do not include a return statement or if you do not specify a value after the keyword return, the value returned by the function is unpredictable.

Does a VBA function have to return a value?

A VBA function can have an optional return statement. This is required if you want to return a value from a function. For example, you can pass two numbers in a function and then you can expect from the function to return their multiplication in your calling program.


2 Answers

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

like image 76
Dan Avatar answered Sep 28 '22 03:09

Dan


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.

like image 28
froadie Avatar answered Sep 28 '22 01:09

froadie