Udostępnij za pośrednictwem


How to: Pass Arguments to a Procedure by Name

When you call a Sub or Function procedure, you can pass arguments to it by name, without regard to the order in which the corresponding parameters appear in the procedure's definition.

Passing arguments by name makes your calling code easier to read because it gives meaning to the argument values in the procedure call. If the procedure has optional parameters, passing by name also makes it easier to keep track of which arguments you are passing and which ones you are omitting.

For rules and restrictions on supplying arguments by name, see Passing Arguments by Position and by Name.

To pass an argument by name

  1. Examine the source code of the procedure's declaration to determine the exact spelling of the parameter names.

  2. In the calling code, prepare the procedure call in the normal way, with the argument list in parentheses following the procedure name.

  3. For each argument you intend to pass by name, supply the parameter's declared name followed by a colon and an equal sign (:=), followed by the value you are passing for the argument.

  4. You can supply named arguments in any order, but you must supply all positional arguments before supplying any named arguments.

Example

The following example shows a Sub procedure with three parameters, and a Call Statement (Visual Basic) that passes arguments to these parameters by name.

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
Call studentInfo(age:=19, birth:=#9/21/1981#, name:="Mary")

When you pass arguments by name, you do not have to supply them in the same order as the procedure declares them.

Compiling the Code

Make sure the parameter name in the argument list exactly matches the name declared by the procedure.

See Also

Tasks

How to: Pass Arguments to a Procedure

Concepts

Procedures in Visual Basic

Procedure Parameters and Arguments

Passing Arguments by Value and by Reference

Passing Arguments by Position and by Name

Optional Parameters

Parameter Arrays

Reference

Optional (Visual Basic)

ParamArray