Passing arrays through ParamArray with user-defined functions

249 Views Asked by At

New to VBA. I'm having two issues with the following code for user defined functions. I can't figure out how to pass arrays through ParamArray.

1) The printed type from bool() is 8203 as it should be. But the printed type from test() is 8204, so they're null or invalid. Edit: it was pointed out that 8204 is due to the Variant type.

2) I'm not sure if I'm calling elements from nested arrays correctly with "A(0)(1,1)". I'm not able to print or call values from A() the the Test() function.

In a cell formula:

=Test(bool())

In VBA editor:

Function Test(ParamArray A() As Variant)
    Debug.Print VarType(A)
    Debug.Print A(0)(1,1)
    Test = A(0)(1, 1)
End Function

Function bool()
    Dim out() As Boolean
    Dim u As Integer, v As Integer

    ReDim out(1 To 3, 1 To 2)
    For v = 1 To 2
        For u = 1 To 3
            out(u, v) = True
        Next u
    Next v

    Debug.Print VarType(out)
    bool = out
End Function

ParamArray is necessary, I'm just not demonstrating why with this example.

3

There are 3 best solutions below

0
kas On BEST ANSWER

The problem was fixed by removing the Debug.Print A(0). And by fixing another typo that was not present in the original post.

1
ProfoundlyOblivious On

8204 is expected because ParamArray A() As Variant is a variant array.

vbVariant = 12
vbArray = 8192

8192 + 12 = 8204

7
user11982798 On

You have two issues, first A(0) is param 1 and the content is out(u,v), so debug.print A(0) will give error, second your function test without return value and for running code are as follow:

Function Test(ParamArray A() As Variant)
    msgbox "1" & ubound(A)
    Debug.Print A(0)(1, 1)
    Test = A(0)(1, 1)
    msgbox "2" & ubound(A)
End Function

Function bool()
    Dim out() As Boolean
    Dim u As Integer, v As Integer

    ReDim out(1 To 3, 1 To 2)
    For v = 1 To 2
        For u = 1 To 3
            out(u, v) = True
        Next u
    Next v

    Debug.Print VarType(out)
    bool = out
End Function