Optional Parameters

You can specify that a procedure parameter is optional and no argument has to be supplied for it when the procedure is called. Optional parameters are indicated by the Optional keyword in the procedure definition. The following rules apply:

  • Every optional parameter in the procedure definition must specify a default value.

  • The default value for an optional parameter must be a constant expression.

  • Every parameter following an optional parameter in the procedure definition must also be optional.

The following syntax shows a procedure declaration with an optional parameter:

Sub sub name(ByVal parameter 1 As data type 1, Optional ByVal parameter 2 As data type 2 = default value)

Calling Procedures with Optional Parameters

When you call a procedure with an optional parameter, you can choose whether to supply the argument. If you do not, the procedure uses the default value declared for that parameter.

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 sub name(argument 1, , , argument 4)

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 defines the optional parameter office, and tests for its default value, QJZ, to see if it has been omitted in the call:

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 optional parameter 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.

Optional Parameters and Overloading

Another way to define a procedure with optional parameters is to use overloading. If you have one optional parameter, you can define two overloaded versions of the procedure, one accepting the parameter and one without it. This approach becomes more complicated as the number of optional parameters increases. However, its advantage is that you can be absolutely sure whether the calling program supplied each optional argument.

See Also

Tasks

How to: Define Optional Parameters for a Procedure

How to: Call a Procedure that Takes Optional Parameters

How to: Determine Whether an Optional Parameter Was Supplied

Concepts

Procedures in Visual Basic

Procedure Parameters and Arguments

Passing Arguments by Value and by Reference

Passing Arguments by Position and by Name

Parameter Arrays

Procedure Overloading

Reference

Optional (Visual Basic)

ParamArray