Dela via


How to: Call a Procedure that Takes Optional Parameters (Visual Basic)

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

  • If you intend to supply the argument, include it in the argument list in the normal way, between commas.

  • If you intend to omit the argument, use successive commas in the argument list to mark its omission.

  • If you omit the argument and you are supplying arguments by name, you do not need to indicate the omitted argument either by name or by commas.

Example

The following example makes several calls to the MsgBox function. MsgBox has one required parameter and two optional parameters.

MsgBox("Important message", MsgBoxStyle.Critical, "MsgBox Example")
MsgBox("Just display this message.")
MsgBox("Test message", , "Title bar text")
MsgBox(Title:="Title bar text", Prompt:="Test message")

The first call to MsgBox supplies all three arguments in the order MsgBox defines them. The second call supplies only the required argument. The third and fourth calls supply the first and third arguments. The third call does this by position, and the fourth call does it by name.

Compiling the Code

Before you omit an argument from the argument list, be sure the corresponding parameter is optional, and also be sure you want the procedure to use the default value for that parameter.

If you supply an argument by name, be sure the name in the argument list exactly matches the declared parameter name.

See Also

Tasks

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

How to: Determine Whether an Optional Parameter Was Supplied (Visual Basic)

Reference

Optional (Visual Basic)

ParamArray (Visual Basic)

Concepts

Procedure Parameters and Arguments (Visual Basic)

Passing Arguments by Value and by Reference (Visual Basic)

Passing Arguments by Position and by Name (Visual Basic)

Optional Parameters (Visual Basic)

Parameter Arrays (Visual Basic)

Procedure Overloading (Visual Basic)