Originally Posted by
MSDN Help for vb6.0
Using Optional Arguments
You can specify arguments to a procedure as optional by placing the Optional keyword in the argument list. If you specify an optional argument, all subsequent arguments in the argument list must also be optional and declared with the Optional keyword. The two pieces of sample code below assume there is a form with a command button and list box.
For example, this code provides all optional arguments:
Dim strName As String
Dim strAddress As String
Sub ListText(Optional x As String, Optional y _
As String)
List1.AddItem x
List1.AddItem y
End Sub
Private Sub Command1_Click()
strName = "yourname"
strAddress = 12345 ' Both arguments are provided.
Call ListText(strName, strAddress)
End Sub
This code, however, does not provide all optional arguments:
Dim strName As String
Dim varAddress As Variant
Sub ListText(x As String, Optional y As Variant)
List1.AddItem x
If Not IsMissing(y) Then
List1.AddItem y
End If
End Sub
Private Sub Command1_Click()
strName = "yourname" ' Second argument is not
' provided.
Call ListText(strName)
End Sub
In the case where an optional argument is not provided, the argument is actually assigned as a variant with the value of Empty. The example above shows how to test for missing optional arguments using the IsMissing function.
Providing a Default for an Optional Argument
It's also possible to specify a default value for an optional argument. The following example returns a default value if the optional argument isn't passed to the function procedure:
Sub ListText(x As String, Optional y As _
Integer = 12345)
List1.AddItem x
List1.AddItem y
End Sub
Private Sub Command1_Click()
strName = "yourname" ' Second argument is not
' provided.
Call ListText(strName) ' Adds "yourname" and
' "12345".
End Sub
...
Creating Simpler Statements with Named Arguments
For many built-in functions, statements, and methods, Visual Basic provides the option of using named arguments as a shortcut for typing argument values. With named arguments, you can provide any or all of the arguments, in any order, by assigning a value to the named argument.
You do this by typing the argument name plus a colon followed by an equal sign and the value
MyArgument:= "SomeValue"
and placing that assignment in any sequence delimited by commas.
Notice that the arguments in the following example are in the reverse order of the expected arguments:
Function ListText(strName As String, Optional strAddress As String)
List1.AddItem strName
List2.AddItem strAddress
End Sub
Private Sub Command1_Click()
ListText strAddress:=”12345”, strName:="Your Name"
End Sub
This is especially useful if your procedures have several optional arguments that you do not always need to specify.
Bookmarks