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

标签 arrays excel vba multidimensional-array resize

我有一个简单的问题:

  • 我有一组数据,我正在筛选并在条件匹配时添加到数组中
  • 问题是,我不知道可能有多少匹配,所以我需要数组的大小未指定。
  • 数组的第二个索引是静态的。

  • 在(伪语言)示例中:
    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
    

    问题是,这会引发异常:

    enter image description here

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

    最佳答案

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

    Dim arr(0, 1 to 3) as String
    
    至:
    Dim arr() as String
    ReDim arr(1 to 3, i)
    
    根据需要重新调整它。
    编辑:
    如需更多信息,请参阅此链接: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.

    关于arrays - 如何创建未知大小的多维数组?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55363541/

    相关文章:

    javascript - 遍历二维数组并找到 "enclosed rooms"

    c++ - 对数组使用算术

    javascript - 无法使函数声明起作用

    python - 使用 openpyxl 查找包含具有特定值的单元格的行

    c# - 尝试读取 Excel 文件中的值时无法在 C# 中找到方法 GetCellValue

    excel - 如何使用 VBA 将页面设置从工作表复制到另一个

    python - 使用 Python 更新 Excel 电子表格中的链接

    c - 使用 strtok() 分解字符串并将其放入数组中

    vba - VBA 代码中出现内存不足错误

    Excel vba 将值分配给数组,然后粘贴到工作表