VBA将3维数组粘贴到表格中

时间:2010-06-18 22:35:34

标签: excel vba multidimensional-array

我有一个三维数组(5 x 5 x 3),我需要将(5 x 5 x 1)发布到Sheet1,(5 x 5 x 2)到Sheet2,(5 x 5 x 3)到Sheet3 。因为我在3个嵌套for循环中构建这个3维数组,所以我不能使用for循环来访问循环的(5 x 5)部分。是否有任何标识符告诉excel索引数组的所有元素,例如在MatLab中使用(1:end,1:end,1)?基本代码如下:

Sub practice_2()

Dim arr(1 To 5, 1 To 5, 1 To 3)
Dim a As Integer
Dim x As Integer
Dim y As Integer

    For a = 1 To 3
        For x = 1 To 5
            For y = 1 To 5
                arr(x, y, a) = x * y
            Next
        Next

        Sheets(a).Select
        'Following line is where I want to access the (5 x 5 x 1) array
        Range(Cells(1, 1), Cells(5, 5)) = arr
    Next
End Sub 

1 个答案:

答案 0 :(得分:6)

在Excel中使用三维数组直接做的事情并不多。但是,VBA Variants非常灵活。你可以通过使用包含2-D数组而不是3-D数组的1-D数组得到你想要的东西:

Dim arr(1 To 3)

Dim a As Integer
Dim x As Integer
Dim y As Integer

For a = 1 To 3
    ReDim inner(1 To 5, 1 To 5)

    'don't worry...makes a copy
    arr(a) = inner

    For x = 1 To 5
        For y = 1 To 5
            arr(a)(x, y) = a * x * y
        Next
    Next

    Sheets(a).Select

    Range(Cells(1, 1), Cells(5, 5)) = arr(a)
Next

(回答你关于数组语法的具体问题,答案是“不”。)