Export (0) Print
Expand All
This topic has not yet been rated - Rate this topic

Passing Arguments by Position and by Name

When you call a Sub or Function procedure, you can pass arguments by position — in the order in which they appear in the procedure's definition — or you can pass them by name, without regard to position.

When you pass an argument by name, you specify the argument's declared name followed by a colon and an equal sign (:=), followed by the argument value. You can supply named arguments in any order.

For example, the following Sub procedure takes three arguments:

Sub studentInfo(ByVal name As String, _
       Optional ByVal age As Short = 0, _
       Optional ByVal birth As Date = #1/1/2000#)

  Debug.WriteLine("Name = " & name & _
                "; age = " & CStr(age) & _
                "; birth date = " & CStr(birth))
End Sub

When you call this procedure, you can supply the arguments by position, by name, or by using a mixture of both.

You can call the procedure studentInfo with its arguments passed by position and delimited by commas, as shown in the following example:

Call studentInfo("Mary", 19, #9/21/1981#)

If you omit an optional argument in a positional argument list, you must hold its place with a comma. The following example calls studentInfo without the age argument:

Call studentInfo("Mary", , #9/21/1981#)

Alternatively, you can call studentInfo with the arguments passed by name, also delimited by commas, as shown in the following example:

Call studentInfo(age:=19, birth:=#9/21/1981#, name:="Mary")

You can supply arguments both by position and by name in a single procedure call, as shown in the following example:

Call studentInfo("Mary", birth:=#9/21/1981#)

In the preceding example, no extra comma is necessary to hold the place of the omitted age argument, since birth is passed by name.

When you supply arguments by a mixture of position and name, the positional arguments must all come first. Once you supply an argument by name, the remaining arguments must all be by name.

Passing arguments by name is especially useful when you call a procedure that has more than one optional argument. If you supply arguments by name, you do not have to use consecutive commas to denote missing positional arguments. Passing arguments by name also makes it easier to keep track of which arguments you are passing and which ones you are omitting.

You cannot pass arguments by name to avoid entering required arguments. You can omit only the optional arguments.

You cannot pass a parameter array by name. This is because when you call the procedure, you supply an indefinite number of comma-separated arguments for the parameter array, and the compiler cannot associate more than one argument with a single name.

Did you find this helpful?
(1500 characters remaining)
Thank you for your feedback

Community Additions

ADD
Show:
© 2014 Microsoft. All rights reserved.