Argument Passing by Position and by Name
When you call a Sub or Function procedure, you can pass arguments by position — that is, 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.
Passing Arguments by Position
You can call the procedure
StudentInfo with its arguments passed by position and delimited by commas, as shown in the following example:
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
StudentInfo("Mary", , #9/21/1981#)
Passing Arguments by Name
Alternatively, you can call
StudentInfo with the arguments passed by name, also delimited by commas, as shown in the following example:
StudentInfo(Age:=19, Birth:=#9/21/1981#, Name:="Mary")
Mixing Arguments by Position and by Name
You can supply arguments both by position and by name in a single procedure call, as shown in the following example:
In the preceding example, no extra comma is necessary to hold the place of the omitted
Age argument, since
Birth is passed by name.
If you supply arguments both by position and by name, the positional arguments must all come first. Once you supply an argument by name, the remaining arguments must all be by name.
Supplying Optional Arguments 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.
Restrictions on Supplying Arguments by Name
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.