Dear John, How Do I... Use Optional Parameters?

Optional parameters are especially useful when you have a relatively long list of parameters for a procedure. Here's a simple modification of the previous example to show you how this works:

Option Explicit

Private Sub FormColor( _
    Optional sngRed = 0, _
    Optional sngGreen = 0, _
    Optional sngBlue = 0 _
)
    BackColor = RGB(sngRed * 256, sngGreen * 256, sngBlue * 256)
End Sub

Private Sub Form_Click()
    FormColor sngGreen:=0.5   `Medium green
End Sub

By adding the keyword Optional to the parameter declarations in the FormColor procedure, you can pass any or all of the parameters as named arguments to clearly indicate which parameters are passed. In this example, I've passed only the sngGreen parameter, knowing that the procedure will default to the value 0 for the optional parameters I didn't pass.

Notice that the default values are set in the parameter list. In Visual Basic 4, you had to check each optional parameter by using an IsMissing function and then setting a default value. Now, optional parameters can accept specific data types other than Variant. However, you still have to be sure that once a parameter is defined with the Optional modifier, all remaining parameters in the list are also declared as optional.

SEE ALSO