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

问题描述 投票:0回答:2

我有一个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 
excel vba multidimensional-array
2个回答
6
投票

在 Excel 中直接使用 3D 数组无法做太多事情。然而,VBA 变体非常灵活。您可以通过使用包含 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

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


0
投票

子粘贴三维数组()

'Declare Array
Dim ArrA(19, 2) As Integer
'Declare & Set Worksheet
Dim ws1 As Worksheet
Set ws1 = Sheets("Sheet1")
'NOTE:  To test, add data to the first 20 rows of Columns A, B, and C
'Read Data into Array
For x = 1 To 20
    ArrA(x - 1, 0) = ws1.Cells(x, 1)
    ArrA(x - 1, 1) = ws1.Cells(x, 2)
    ArrA(x - 1, 2) = ws1.Cells(x, 3)
Next
'A single WorksheetFunction.Transpose will add your data horizontally
ws1.Range("E1:X3") = WorksheetFunction.Transpose(ArrA)
'A double WorksheetFunction.Transpose will add your data vertically
ws1.Range("Z1:AB20") = WorksheetFunction.Transpose(WorksheetFunction.Transpose(ArrA))

结束子

© www.soinside.com 2019 - 2024. All rights reserved.