VBA Redim Preserve

时间:2017-02-15 18:50:56

标签: arrays excel vba excel-vba multidimensional-array

我不知道如何填充多维数组。这是我的代码,我刚刚开始理解,但我不知道什么是错的,除了一个循环它是不工作的。

Sub test()
    Dim Arr1 As Variant
    Dim Row As Long
    For Row = 0 To 3            
        ReDim Arr1(9, Row)
        Arr1(0, Row) = "Zero"
        Arr1(1, Row) = "One"
        Arr1(2, Row) = "Two"
        Arr1(3, Row) = "Three"
        Arr1(4, Row) = "Four"
        Arr1(5, Row) = "Five"
        Arr1(6, Row) = "Six"
        Arr1(7, Row) = "Seven"
        Arr1(8, Row) = "Eight"
        Arr1(9, Row) = "Nine"    
        Row = Row + 1
        ReDim Preserve Arr1(9, Row)        
    Next Row
    MsgBox Arr1(0, 0)
End Sub

由于

2 个答案:

答案 0 :(得分:2)

试试这个:

Sub test()
    Dim limit As Integer
    limit = 3 'get limit from somewhere

    Dim Arr1 as Variant        
    Redim Arr1(0 To 9, 0 To limit) As Variant

    Dim Row As Long
    For Row = 0 To 3            
        Arr1(0, Row) = "Zero"
        Arr1(1, Row) = "One"
        Arr1(2, Row) = "Two"
        Arr1(3, Row) = "Three"
        Arr1(4, Row) = "Four"
        Arr1(5, Row) = "Five"
        Arr1(6, Row) = "Six"
        Arr1(7, Row) = "Seven"
        Arr1(8, Row) = "Eight"
        Arr1(9, Row) = "Nine"        
    Next Row
    MsgBox Arr1(0, 0)
End Sub

您已经知道阵列所需的限制,因此只需在开始时定义限制即可。您不需要在任何其他方面重新定义这些内容。

另外,Next RowRow=Row+1做同样的事情,所以你不想要两者

<强>更新

如果您愿意,也可以将字符串放在数组中

Sub test()
    Dim limit As Integer
    limit = 3 'get limit from somewhere

    Dim Arr1 as Variant        
    Redim Arr1(0 To 9, 0 To limit) As Variant

    Dim numbers As Variant
    numbers = Array("Zero", "One", "Two", "Three", "Four", "Five", "Six", "Seven", "Eight", "Nine")

    Dim Row As Integer, Col As Integer
    For Row = 0 To 3
        For Col = 0 To 9
            Arr1(Col, Row) = numbers(Col)
        Next Col
    Next Row
    MsgBox Arr1(0, 0)
End Sub

更新2

真的有很多方法可以给猫皮肤...... 如何使用集合:

Sub test()
    Dim numbers As Variant
    numbers = Array("Zero", "One", "Two", "Three", "Four", "Five", "Six", "Seven", "Eight", "Nine")

    Dim col As Collection
    Set col = New Collection

    Dim i As Integer
    For i = 0 To 3 'get limit from somewhere
        col.Add numbers
    Next i

    MsgBox col(1)(0)  'col(1 to 4)(0 to 9)
End Sub

答案 1 :(得分:2)

可以使用范围重复它们而不需要循环:

Dim r As Range, Arr1
Set r = Cells.Resize(10, 4)

r = [{"Zero";"One";"Two";"Three";"Four";"Five";"Six";"Seven";"Eight";"Nine"}]     
Arr1 = r           ' Arr1 is now (1 To 10, 1 To 4) As Variant
r.ClearContents