VBA 3维数组

时间:2016-10-02 21:28:46

标签: excel-vba vba excel

我必须使用嵌套的For / Next循环来填充一个多维数组,该数组包含前三张纸上范围A1:E5的数据。然后我想在当前工作表上显示数组。这是为了课堂,这本书实际上并没有涵盖使用三维数组。

Private Sub multiWorksheetArray_Click()

Dim multiSheetArray(2, 4, 4) As Variant 'array with 3 sheets, 5 columns/rows
Dim I As Integer 'counters
Dim J As Integer
Dim S As Integer


For S = 1 To 3
    For I = 1 To 5
        For J = 1 To 5
           'populate the array
            multiArray(S - 1, J - 1, I - 1) = ActiveWorkbook.Worksheets("Sheet" + S).Cells(J, I).Value
        Next J
    Next I
Next S

Range("A15:O19").Value = multiArray

End Sub

2 个答案:

答案 0 :(得分:1)

存储数据的实际方法是使用2D阵列填充一维阵列。这将允许您使用标准技术来处理数据。

Sub Test3DArray()
    Dim w As Long, x As Long, y As Long, z As Long
    Dim c As Range
    Dim v(4, 4) As Variant
    Dim multiSheetArray(2) As Variant    'array with 3 sheets, 5 columns/rows

    multiSheetArray(0) = v
    multiSheetArray(1) = v

    For w = 1 To 2
        With Worksheets(w)
            For x = 1 To 5
                For y = 1 To 5
                    multiSheetArray(w - 1)(x - 1, y - 1) = .Cells(x, y)
                Next
            Next
        End With
    Next

    multiSheetArray(2) = Worksheets(3).Range("A1:E5").Value

    With Worksheets(4)
        .Range("A1:E5").Value = multiSheetArray(0)

        .Range("A1:E5").Offset(6).Value = multiSheetArray(1)

        .Range("A1:E5").Offset(12).Value = multiSheetArray(2)
    End With

End Sub

结果:

enter image description here

答案 1 :(得分:0)

设置:我将前3张中Range(“A1:E5”)中每个单元格的值设置为外部地址:

Sub Setup()
    Dim w As Long
    Dim c As Range

    For w = 1 To 3
        For Each c In Worksheets(i).[A1:E5]
            c = c.Address(External:=True)
        Next
    Next
End Sub

测试:迭代3D数组中的每个元素并推送它并将元素的值推入3个单元格宽的范围内。因为For Each Loops逐列遍历其元素,并且逐行遍历范围边界的范围填充值,所以这些值将自然填充。

Sub Test3DArray()
    Dim w As Long, x As Long, y As Long, z As Long
    Dim c As Range
    Dim v As Variant
    Dim multiSheetArray(2, 4, 4) As Variant    'array with 3 sheets, 5 columns/rows

    For w = 1 To 3
        With Worksheets(w)
            For x = 1 To 5
                For y = 1 To 5
                    multiSheetArray(w - 1, x - 1, y - 1) = .Cells(x, y)
                Next
            Next
        End With
    Next

    For Each v In multiSheetArray
        With Worksheets(4)
            z = z + 1
            .Range("A1:C1").Cells(z) = v
        End With
    Next
End Sub

结果

enter image description here