如何创建未知大小的多维数组?

How to create multi-dimensional array of unknown size?

我有一个简单的问题:

在一个(伪语言)例子中:

if <matched criteria> = True {
    i = i + 1
    array( i,  1 ) => "John Doe" ' name
    array( i,  2 ) => "New York" ' location
    array( i,  3 ) => "02. 08. 1992" ' birthdate
}

问题是,在 中,您必须预先声明数组(尤其是启用 Option Explicit 时)。我的想法是声明一个数组,该数组将从 0 处的第一个索引开始,然后根据需要逐渐 ReDim 它。

这是我的代码的一个简化示例:

Dim cell as Range
Dim arr(0, 1 to 3) as String
Dim i As Integer: i = 0

For each cell in Range("A1:A100")
  If criteria_match(cell) = True Then
      arr(i, 1) = Cells(cell.row, 4)
      arr(i, 2) = Cells(cell.row, 5)
      arr(i, 3) = Year(Cells(cell.row, 6))
      i = i + 1
      ReDim Preserve arr(i, 1 to 3)
  End If
Next cell

问题是,这会引发异常:

有什么办法可以根据需要稳步增加第一个数组索引的大小吗?

不要在变量声明语句中调整数组大小。

变化:

Dim arr(0, 1 to 3) as String

至:

Dim arr() as String
ReDim arr(1 to 3, i)

根据需要重新调整尺寸。

编辑: 有关详细信息,请参阅此 link:https://docs.microsoft.com/en-us/office/vba/language/reference/user-interface-help/array-already-dimensioned

简而言之,当您在声明语句中调整数组大小时,它会创建一个静态数组(无法调整大小)。当你不声明大小时,它就变成了一个动态数组,可以调整大小。


An important note to make: ReDim Preserve can only be applied on the last dimension of the array

eg. ReDim Preserve arr(1 to 3, i) will work.
Meanwhile, ReDim Preserve arr (i, 1 to 3) will not.

根据类型为数据使用类型,为变量使用集合。

Class Person

Public Name As String
Public Location As String
Public DoB As Date

在模块中

Sub Test()

    Dim this_person As Person
    Dim Persons As Collection
    Dim my_cell                 As Excel.Range
    Set Persons = New Collection

    For Each my_cell In Range("A1:A100")

      If Criteria_Match(my_cell) Then

        Set this_person = New Person
        With this_person

            .Name = ActiveWorkbook.ActiveWorksheet.Cells(my_cell.Row, 4).Value2
            .Location = ActiveWorkbook.ActiveWorksheet.Cells(my_cell.Row, 5).Value2
            .DoB = Year(ActiveWorkbook.ActiveWorksheet.Cells(my_cell.Row, 6).Value2)

        End With

        Persons.Add this_person

      End If

    Next

End Sub