You can specify that a procedure argument is optional and does not have to be supplied when the procedure is called. Optional arguments are indicated by the Optional keyword in the procedure definition. The following rules apply:
- Every optional argument in the procedure definition must specify a default value.
- The default value for an optional argument must be a constant expression.
- Every argument following an optional argument in the procedure definition must also be optional.
The following syntax shows a procedure declaration with an optional argument:
Sub subname(ByVal arg1 As type1, Optional ByVal arg2 As type2 = default)
Calling Procedures with Optional Arguments
When you call a procedure with an optional argument, you can choose whether to supply the argument. If you do not, the procedure uses the default value declared for that argument.
When you omit one or more optional arguments in the argument list, you use successive commas to mark their positions. The following example call supplies the first and fourth arguments but not the second or third:
Call subname(arg1, , , arg4) ' Leaves out arg2 and arg3.
Determining Whether an Optional Argument Is Present
A procedure cannot detect at run time whether a given argument has been omitted or the calling code has explicitly supplied the default value. If you need to make this distinction, you can set an unlikely value as the default. The following procedure includes the optional argument
Office, and tests for its default value,
QJZ, to see if it has been omitted:
Sub Notify(ByVal Company As String, Optional ByVal Office As String = "QJZ") If Office = "QJZ" Then Debug.WriteLine("Office not supplied -- notifying Headquarters") Office = "Headquarters" End If ' Code to notify headquarters or specified office. End Sub
If the optional argument is a reference type such as a String, you can use Nothing as the default value, provided this is not an expected value for the argument.
Another way to define a procedure with optional arguments is to use overloading. If you have one optional argument, you can define two overloaded versions of the procedure, one with the argument and one without it. This approach becomes more complicated as the number of optional arguments increases. However, its advantage is that you can be absolutely sure whether the calling program supplied each optional argument.
Procedures | Procedure Arguments | Argument Data Type Declaration | Argument Passing ByVal and ByRef | Argument Passing by Position and by Name | Parameter Arrays | Procedure Overloading | Considerations in Overloading Procedures | Optional