简体   繁体   中英

Passing arrays through ParamArray with user-defined functions

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.

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

vbVariant = 12
vbArray = 8192

8192 + 12 = 8204

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM