How to: Define Optional Parameters for a Procedure
You can specify that a procedure parameter is optional, so that the calling code does not have to supply an argument for it when it calls the procedure. When you do this, you define a default value that the procedure uses if the argument is not supplied.
You can define more than one optional parameter, but all the optional parameters must be at the end of the parameter list. All the required parameters must precede every optional parameter.
To define an optional parameter
In the procedure declaration, precede the parameter name in the parameter list with the Optional keyword.
Follow the parameter name with an As clause as usual, and follow the As clause with an equal sign (=).
Follow the equal sign with the default value for the parameter. This must be a constant expression, so that the compiler can completely evaluate it at compile time.
You must declare every subsequent parameter as Optional.
Example
The following example shows a procedure declaration with an optional parameter.
Sub notify(ByVal company As String, Optional ByVal office As String = "QJZ")
If office = "QJZ" Then
Debug.WriteLine("office not supplied -- using Headquarters")
office = "Headquarters"
End If
' Insert code to notify headquarters or specified office.
End Sub
If the calling code does not supply a value for office in the argument list, Visual Basic supplies the default value of "QJZ".
Compiling the Code
You must specify a default value for every optional parameter in the procedure declaration. Be sure that each default value is a constant that the compiler can evaluate at compile time.
See Also
Tasks
How to: Call a Procedure that Takes Optional Parameters
How to: Determine Whether an Optional Parameter Was Supplied
Concepts
Procedure Parameters and Arguments
Passing Arguments by Value and by Reference
Passing Arguments by Position and by Name