Partilhar via


Como: Definir parâmetros opcionais para um procedimento (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.

Exemplo

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

Compilando o código

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.

Consulte também

Tarefas

Como: Chamar um procedimento que recebe parâmetros opcionais (Visual Basic)

Como: Determinar se um parâmetro opcional foi fornecido (Visual Basic)

Referência

Opcional (Visual Basic)

ParamArray (Visual Basic)

Conceitos

Parâmetros e argumentos de procedimento (Visual Basic)

Passando argumentos por valor e por referência (Visual Basic)

Passagem de argumentos por posição e nome (Visual Basic)

Parâmetros opcionais (Visual Basic)

Matrizes de parâmetros (Visual Basic)

Sobrecarga de procedimento (Visual Basic)