exceluser-defined-functionsparamarrayvba

Missing ParamArray in a UDF


I'm trying to determine when a user defined function (UDF) using a ParamArray has been used on the worksheet with no ParamArray parameter(s) supplied.

I've tried the IsEmpty, IsArray, IsError, comparing to nothing, comparing to a zero-length string, etc.

I'm aware that a paramarray is always byVal and that the variant array is always zero-based, but if it doesn't exist, how is it an array?

testParams UDF:

Public Function testParams(ByRef ndx As Long, ParamArray tests())
    Select Case ndx
        Case 1
            testParams = CBool(tests(LBound(tests)) Is Nothing)
        Case 2
            testParams = IsEmpty(tests)
        Case 3
            testParams = IsArray(tests)
        Case 4
            testParams = IsError(tests)
        Case 5
            testParams = CBool(tests(LBound(tests)) = vbNullString)
    End Select
End Function

In the following example, I am simply returning to the worksheet what trying to access the ParamArray returns.

enter image description here

How can I determine if the user has not provided the ParamArray parameter(s) in a real-world UDF that requires them? I would prefer a simple boolean check vs. testing against testing whether something is nothing.


Solution

  • An excellent explanation of Array Allocation is at http://www.cpearson.com/Excel/IsArrayAllocated.aspx

    Excert:

    The function below, IsArrayAllocated will accurately return True or False indicating whether the array is allocated. This function will work for both static and dynamic arrays of any number of dimensions, and will correctly work for unallocated arrays with valid (non-error-causing) LBound values

    And the function

    Function IsArrayAllocated(Arr() As Variant) As Boolean
        On Error Resume Next
        IsArrayAllocated = IsArray(Arr) And _
            Not IsError(LBound(Arr, 1)) And _
            LBound(Arr, 1) <= UBound(Arr, 1)
    End Function
    

    Using it with a Functionwith a Parameter Array

    Function MyFunc(ParamArray pa()) As Variant
        Dim v()
        v = pa
        If IsArrayAllocated(v) Then
            'Do stuff with the parameters
        Else
            'There are no parameters...
        End If
    End Function