' The following user-defined function returns the square root of the ' argument passed to it.Function
CalculateSquareRoot(
NumberArgAs
Double)
As
Double If NumberArg < 0 Then ' Evaluate argument.Exit Function
' Exit to calling procedure. Else CalculateSquareRoot = Sqr(NumberArg) ' Return square root. End IfEnd Function
Using the ParamArray keyword enables a function to accept a variable number of arguments. In the following definition, FirstArg
is passed by value.
Function
CalcSum(ByVal
FirstArgAs
Integer,
ParamArray
OtherArgs())
Dim ReturnValue ' If the function is invoked as follows: ReturnValue = CalcSum(4, 3 ,2 ,1) ' Local variables are assigned the following values: FirstArg = 4, ' OtherArgs(1) = 3, OtherArgs(2) = 2, and so on, assuming default ' lower bound for arrays = 1.
Optional arguments can have default values and types other than Variant.
' If a function's arguments are defined as follows:Function
MyFunc(
MyStrAs
String,
Optional
MyArg1As
_Integer =
5,
Optional
MyArg2=
"Dolly")
Dim RetVal ' The function can be invoked as follows: RetVal = MyFunc("Hello", 2, "World") ' All 3 arguments supplied. RetVal = MyFunc("Test", , 5) ' Second argument omitted. ' Arguments one and three using named-arguments. RetVal = MyFunc(MyStr:="Hello ", MyArg1:=7)