Optional Arguments

Arguments to a procedure or function can be specified as optional.
You can specify as many optional arguments as you like although they must come at the end of the parameter list.
A procedure (or function) can have any number of optional arguments, but they must all come at the end of the parameter list.
If we omit an optional argument in the middle of a list, we must include an empty space when calling that procedure.


Default Values

When a parameter has been declared with the Optional keyword you can call the procedure (or function) with or without an argument for this parameter.
There are two methods you can use when you want to use optional arguments
The arguments to a procedure can be specified as being optional by using the Optional keyword.
The actual parameter is not optional but specifying the value is.
When you declare a parameter as being optional you must always define its default value.
Any optional arguments will contain their default values if they are not explicitly passed in.
If you have an optional integer argument there is no way of telling if zero has been explicitly passed or whether it is just the default value
If you have an optional "Variant" argument you can use the ISMISSING function to test if a value has been passed in or not.

Public Sub Procedure_One() 
   Call Procedure_Two("Wingdings", 20)
   Call Procedure_Two
End Sub

Public Sub Procedure_Two(Optional ByVal sFontName As String = "Arial", _
                         Optional ByVal vFontSize As Variant)

   If IsMissing(sFontName) = True Then
        Call MsgBox("sFontName was not provided, so default value has been used")
   End If

   If IsMissing(vFontSize) = True Then
        Call MsgBox("vFontSize was not provided")
   End If
End Sub

Public Sub Procedure_One() 
   Call Procedure_Two("Wingdings", 20)
End Sub

Public Sub Procedure_One(Optional ByVal sFontName As String = "Arial", _
                         Optional ByVal sngFontSize As Single)
   Call Procedure_Two(sFontName, sngFontSize)
End Sub

Important

Remember that ISMISSING will only work with the Variant datatype.
It does not make sense to say that a parameter is optional. It is the value (or argument) that is optional, not the parameter.
A procedure (or function) can have any number of optional arguments.


© 2024 Better Solutions Limited. All Rights Reserved. © 2024 Better Solutions Limited TopPrevNext