Export (0) Print
Expand All
1 out of 1 rated this helpful - Rate this topic

How to: Define Optional Parameters for a Procedure (Visual Basic)

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

  1. In the procedure declaration, precede the parameter name in the parameter list with the Optional keyword.

  2. Follow the parameter name with an As clause as usual, and follow the As clause with an equal sign (=).

  3. 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.

  4. You must declare every subsequent parameter as Optional.

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".

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.

Did you find this helpful?
(1500 characters remaining)
Thank you for your feedback

Community Additions

ADD
Show:
© 2014 Microsoft. All rights reserved.