Optional parameters

Optional parameters must not be declared on function call.

Example:

 

Public Function DoAny(Optional ByVal P1 As Long) As Long

                If IsMissing(P1) Then

                                Return 200

                EndIf

                Return 100

End Function

The call of the function above can be executed without parameter

DoAny()

or can be executed with parameter

DoAny(10)

It can be archieved by the function IsMissing if the parameter will be used by caller.

 

If mandatory parameters and optional parameters are defined together, the optional parameters must be specified at the end of the function definition.

Public Function DoAny(ByVal P1 As Long, Optional ByVal P2 As Long, Optional ByVal P3 As Long) As Long

                Return -1 If IsMissing(P2)

                Return -2 If IsMissing(P3)

                Return P1 + P2 + P3

End Function

 

Optional parameters can be given a default value. This eliminates the test for existence with the IsMissing function.

Public Function DoAny(Optional ByVal P1 As Long := 100) As Long

                Return P1

End Function