我有一个简单的问题:
在(伪语言)示例中:
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
}
问题是,在vba中,您必须预先声明数组(尤其是启用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
问题是,这引发了异常:
答案 0 :(得分:3)
不要在变量声明语句中调整数组大小。
更改:
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
为了简要总结一下,当您在声明语句中调整数组大小时,它会创建一个静态数组(无法调整大小)。如果不声明大小,则它将变为动态数组,可以调整大小。
重要说明:
ReDim Preserve
仅适用于数组的最后一个维度例如
ReDim Preserve arr(1 to 3, i)
将起作用。
同时,ReDim Preserve arr (i, 1 to 3)
不会。
答案 1 :(得分:2)
对数据使用类型,对基于类型的变量使用集合。
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