I've used the ParamArray
statement for years when I wanted to accept a variable number of arguments. One good example is this MinVal function:
Function MinVal(ParamArray Values() As Variant)
Dim ReturnVal As Variant, v As Variant
If UBound(Values) < 0 Then
ReturnVal = Null
Else
ReturnVal = Values(0)
For Each v In Values
If v < ReturnVal Then ReturnVal = v
Next v
End If
MinVal = ReturnVal
End Function
' Debug.Print MinVal(10, 23, 4, 17)
' 4
This could be re-written without the ParamArray as:
Function MinVal(Optional Values As Variant)
Dim ReturnVal As Variant, v As Variant
If IsMissing(Values) Or IsNull(Values) Then
ReturnVal = Null
Else
ReturnVal = Values(0)
For Each v In Values
If v < ReturnVal Then ReturnVal = v
Next v
End If
MinVal = ReturnVal
End Function
' Debug.Print MinVal(Array(10, 23, 4, 17))
' 4
Note in the second example use of the Array()
function in the call to MinVal.
The second approach has the advantage of being able to pass the parameter array to another function that also accepts arrays. This provides flexibility if I ever wanted to be able to pass the parameter array in MinVal
on to some other function.
I've begun thinking I should always favor this approach and just stop using ParamArray
altogether.
One could argue that using ParamArray
makes for more explicitly readable code. However, there's no advantage in compile-time checks because ParamArray
must be an array of Variants. Can anyone offer a compelling reason to ever use ParamArray
?