Export (0) Print
Expand All

Parameter Arrays

Usually, you cannot call a procedure with more arguments than the procedure declaration specifies. When you need an indefinite number of arguments, you can declare a parameter array, which allows a procedure to accept an array of values for an argument. You do not have to know the number of elements in the parameter array when you define the procedure. The array size is determined individually by each call to the procedure.

You use the ParamArray keyword to denote a parameter array. The following rules apply:

  • A procedure can have only one parameter array, and it must be the last argument in the procedure definition.
  • The parameter array must be passed by value. It is good programming practice to explicitly include the ByVal keyword in the procedure definition.
  • The code within the procedure must treat the parameter array as a one-dimensional array, each element of which is the same data type as the ParamArray data type.
  • The parameter array is automatically optional. Its default value is an empty one-dimensional array of the parameter array's element type.
  • All arguments preceding the parameter array must be required. The parameter array must be the only optional argument.

When you call a procedure with a parameter array argument, you can pass any of the following for the parameter array:

  • Nothing — that is, you can omit the ParamArray argument. In this case, an empty array is passed to the procedure. You can also pass the Nothing keyword, with the same effect.
  • A list of an indefinite number of arguments, separated by commas. The data type of each argument must be implicitly convertible to the ParamArray element type.
  • An array with the same element type as the parameter array.

The following example shows how you can define a procedure with a parameter array:

Sub StudentScores(ByVal Name As String, ByVal ParamArray Scores() As String)
   Dim I As Integer
   Debug.WriteLine("Scores for " & Name & ":")
   ' Use UBound function to determine largest subscript of array.
   For I = 0 To UBound(Scores)
      Debug.WriteLine("Score " & I & ": " & Scores(I))
   Next I
End Sub

The following examples show typical calls to StudentScores:

StudentScores("Anne", "10", "26", "32", "15", "22", "24", "16")
StudentScores("Mary", "High", "Low", "Average", "High")
Dim JohnScores() As String = {"35", "Absent", "21", "30"}
StudentScores("John", JohnScores)

See Also

Procedures | Procedure Arguments | Argument Data Type Declaration | Argument Passing ByVal and ByRef | Argument Passing by Position and by Name | Optional Arguments | Type Checking | Arrays | ParamArray | ByVal | Optional | UBound Function

Show:
© 2014 Microsoft