Search notes:

VBA: paramArray

The paramArray keyword allows to pass an arbitrary number of arguments to a sub or function.
The following example calculates the sum of the passed parameters:
option explicit

sub main() ' {
    debug.print sum(5.1, 2.29, -3.97, 8)
end sub ' }

function sum(paramArray nums()) as double ' {

    dim i as long

    sum = 0

    for i = lBound(nums) to uBound(nums)
        sum = sum + nums(i)
    next i

end function ' }
Github repository about-VBA, path: /language/subs-and-functions/parameters/paramArray/sum.bas

Passing on a paramArray

The following example tries to call a function that takes a paramArray which in turn calls another function which takes a paramArray.
It turns out that the array that the first function receives is passed on to the second function as the first element in a single element array.
Because the second function (sum in our case) is also called directly, it first needs to check whether the first element in the received parameter is an array or not.
option explicit

sub main() ' {
    debug.print sum              (1,2,3,4,5    )
    debug.print sumViaAnotherFunc(1,2,3,4,5,6,7)
end sub ' }

function sumViaAnotherFunc(paramArray v()) as long ' {
  '
  ' Calling sum().
  ' Since sum() takes a paramArray, it will receive an array with one element
  ' which happens to be the array passed to sumViaAnotherFunc.
  '
    sumViaAnotherFunc = sum(v)
end function ' }

function sum(paramArray v() as variant) as long ' {

    dim i as long

    dim v_ as variant

  '
  ' We need to check if sum was called directly or indirectly.
  ' If called directly, the first element of v is not array,
  ' otherwise it is. Depending on our check, we assign
  ' v or v(0) to v_:
  '
    if isArray(v(0)) then v_ = v(0) _
    else                  v_ = v

  '
  ' Calculating the sum for v.
  '
    sum = 0
    for i = lBound(v_) to uBound(v_)
        sum = sum+v_(i)
    next i

end function ' }
Github repository about-VBA, path: /language/subs-and-functions/parameters/paramArray/call-via.bas

See also

A paramArray parameter cannot be declared to be optional as well (this link).
Passing an array to a function
Arrays

Index