多维数组未从函数传递(excel VBA)

时间:2014-10-06 03:07:35

标签: excel-vba vba excel

在下面的函数中,我构建了一个5乘2的数组。语法是

[代码]

function alpha( code)

dim ancestors(5,2)
(code)

dim result(11)
result(8) = code
result(9) = ancestors
result(10) = code

alpha = result


end function

sub 

dim ancestors5(5,2)
alpha_result = alpha( code )

ancestors5(5,2) = alpha_result(9)


end sub

[/代码]

更简单的代码如下:

function alpha(code) as variant

dim arr(5,2)

result(1) = arr
result(2) = something_else
alpha = arr

end function

sub

dim arr2(5,2)

call = alpha(code)

arr2(5,2) = call(1)

end sub

temp =

从屏幕截图中可以看出,alpha_result(9)数组肯定存在一些内容,但它没有传递给ancestors5数组。

enter image description here

enter image description here

1 个答案:

答案 0 :(得分:1)

这是你的意思吗?

Function Alpha()
Dim a(5, 2)
Dim b(11)

    a(1, 1) = "test" 'e.g.
    b(9) = a

    Alpha = b
End Function

Sub tester()
    Dim arr, arr2  ' Variants
    Dim arr3(5, 2) ' declare empty array with dimensions 0-5, 0-2

    arr = Alpha() '>> arr is now a 1-d array with dimensions 0-11

    MsgBox arr(9)(1, 1) '>> "test" value from 2-d array stored at
                        '    arr(9)
    'or...
    arr2 = arr(9)     'arr2 is now a 2-d array with dimensions 0-5, 0-2
    MsgBox arr2(1, 1) '>> "test"

    ' it's unclear what you *want* to happen here:
    arr3(5, 2) = arr(9) '<< here you're assigning the 2-d array
                        '   stored in arr(9) to the element of
                        '   arr3() at 5,2
End Sub