如何创建未知大小的多维数组? [英] How to create multi-dimensional array of unknown size?
问题描述
我有一个简单的问题:
- 我有一组数据,正在筛选并添加
- 问题是,我不知道可能有多少个匹配项,所以我需要数组的大小不确定。
- 数组的第二个索引是静态的。
在(伪语言)中例如:
如果<匹配的条件> =真{
i = i + 1
array(i,1)=> John Doe’name
array(i,2)=> 纽约的位置
array(i,3)=> 02. 08. 1992'生日
}
问题是,在
也许有什么办法,我可以稳定地增加第一个数组索引取决于
不要在变量声明语句中调整数组大小。
更改:
Dim arr(0,1 to 3)as String
至:
Dim arr()as String
ReDim arr(1 to 3,i)
根据需要对其进行更改。
编辑:
有关更多信息,看到此链接: https://docs.microsoft.com/zh-cn/office/vba/language/reference/user-interface-help/array-already-dimensioned
要简要总而言之,当您在声明语句中调整数组大小时,它将创建一个静态数组(无法调整大小)。当您不声明大小时,它将变为动态数组,可以调整大小。
重要说明制作:
ReDim Preserve
只能应用于数组的最后一个维度
例如。
ReDim Preserve arr(1到3,i)
将起作用。
同时,ReDim Preserve arr(i,1 to 3)
不会。
I've got a simple problem:
- I've got a set of data, which I'm sifting through and adding into an array upon criteria match
- Issue is, I don't know how many matches there might be, so I need the array to be of unspecified size.
- The second index of the array is static.
In an (pseudo-language) example:
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
}
Issue is, in vba you have to kind of pre-declare the arrays (especially with Option Explicit
enabled). My thought process was to declare an array, that would start with first index at 0
and I would gradually ReDim
it upon need.
Here is an simplified example of my code:
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
Issue is, this throws an exception:
Is there perhaps any way, I could steadily increase the size of the first array index depending on the need?
Don't size the array in the variable declaration statement.
Change:
Dim arr(0, 1 to 3) as String
to:
Dim arr() as String
ReDim arr(1 to 3, i)
Redimension it as necessary.
Edit: For more information, see this link: https://docs.microsoft.com/en-us/office/vba/language/reference/user-interface-help/array-already-dimensioned
To briefly summarize, when you size the array in the declaration statement, it creates a static array (which can't be resized). When you don't declare a size, then it becomes a dynamic array, which can be resized.
An important note to make:
ReDim Preserve
can only be applied on the last dimension of the arrayeg.
ReDim Preserve arr(1 to 3, i)
will work.
Meanwhile,ReDim Preserve arr (i, 1 to 3)
will not.
这篇关于如何创建未知大小的多维数组?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!