Optional Arguments

You can specify that a procedure argument is optional by using the Optional keyword before ByVal or ByRef in the d eclaration of the argument, and supplying the argument with a default value. An optional argument does not have to be passed when the procedure is called. In that event, its default value is passed automatically. However, if the argument is passed when the procedure is called, the value passed is used instead of the default value, and the procedure executes as if no optional argument was declared.

For example, you can modify the Power function previously discussed to make the exponent argument optional:

Private Function Power(ByVal num As Integer, _

Optional ByVal exponent As Integer = 2) As Double

Return num A exponent

End Function

If the second argument is not passed Debug.Write(Power(3))

then the default value of the exponent argument, 2, is used, and the output will be 9. However, if a value is passed for the exponent argument, that value is used instead of the default value. Thus, the following call to the Power function would output 27: Debug.Write(Power(3, 3))

The rules for using optional arguments are:

■ Every optional argument in the procedure definition must specify a default value.

■ The default value for an optional argument must be a constant expression.

■ Every argument following an optional argument in the procedure definition must also be optional.

In the example using the Power function, there was only one optional argument. However, sometimes you have several optional arguments, and you may want to supply values for some of them but not for others preceding them. For example, a procedure may havefour arguments, for name, title, office, and bonus. Only the name argument is mandatory, the other three being optional, and you want to pass values for the name and bonus arguments, but not title and office arguments.

If you pass the values by position, you use successive commas to mark the positions of the omitted values. The following call supplies the mandatory name argument and the fourth, and optional, bonus argument, but not the optional title and office arguments:

Passing arguments by name is especially useful here, as you can avoid having to use consecutive commas to denote missing positional arguments:

Call HirePerson(name = "Fred", bonus = 0)

Passing arguments by name also makes it easier to keep track of which arguments you are passing and which ones you are omitting.

1-Minute Drill

■ Do you have to specify a value for an optional argument?

Yes.

■ Can optional arguments be declared to the left or to the right of mandatory arguments?

Every argument following an optional argument in the procedure definition must also be optional. Therefore, optional arguments can only be declared to the right of mandatory arguments.

Was this article helpful?

0 0

Post a comment