vba VBA将3维数组粘贴到工作表中

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/3073486/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-11 11:45:26  来源:igfitidea点击:

VBA pasting 3 dimensional array into sheet

excelvbamultidimensional-array

提问by Michael

I have a 3 dimensional array (5 x 5 x 3) and I need to post (5 x 5 x 1) to Sheet1, (5 x 5 x 2) to Sheet2, (5 x 5 x 3) to Sheet3. Because I am building this 3 dimensional array inside 3 nested for loops, I cannot use a for loop to access the (5 x 5) part of the loop. Is there any identifier that tells excel to index all elements of an array, such as in MatLab by using (1:end, 1:end, 1)? Basic code is below:

我有一个 3 维数组 (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 

回答by jtolle

There's not much you can do directly with a 3-D array in Excel. However, VBA Variants are pretty flexible. You could get what you want by using a 1-D array that contains 2-D arrays instead of a 3-D array:

在 Excel 中直接使用 3-D 数组没有多少事情可以做。但是,VBA 变体非常灵活。您可以通过使用包含二维数组而不是 3 维数组的一维数组来获得所需的内容:

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

(In answer to your specific question about array syntax, the answer is "no".)

(在回答您关于数组语法的具体问题时,答案是“否”。)