Returning a value

  • Thread starter Thread starter NewGuy100
  • Start date Start date
N

NewGuy100

How do you return a value from a function or sub in VBA? The book I a
using is not real clear on this. Can you provide an example
 
As an example

Function myFunc(myVal)
myFunc = myVal * 2
End Function

Then you call like so

Msgbox myFunc(12)

Obviously the function should do more than that, but somewhere within it,
you have to pass the determined result back through the function name
(myFunc = myVal * 2) in my example. Usually, a variable is used within the
function to calculate that value and then pass it back through as the last
statement in the function.

The function can take multiple arguments, I only gave one in this simple
example.

You can also declare what type of variable the function returns, such as

Function myFunc(myVal) As Long

and also type the arguments so as to ensure data integrity in the caller,
such as

Function myFunc(myVal As Long) As Long
 
A simple example:

Option explicit
Function myFunction(myValue1 as double, myValue2 as double) as double
myfunction = myvalue1 * myvalue2
end function

Just assign the value you want returned to the function name.
 
Thanks for the tip. It helped a lot. The book I am currently using doe
not help. It doesn't even mention functions or methods in the index
 
Back
Top