动态地将元素推送到数组的末尾

时间:2015-12-11 15:24:11

标签: arrays vba excel-vba excel

有没有办法将元素二进制推送到数组的末尾? 与array.push中的Javascript VBA类似?

我需要将元素推送到数组的末尾,但我不知道它的大小。

Option Explicit

Sub Macro1()
Dim similarValues() As Integer
Dim j As Integer

For j = 1 To 10
    if "condition" then
    ReDim Preserve similarValues("lenght of the array")
    similarValues("lenght of the array") = j
    End if
Next j

End Sub

1 个答案:

答案 0 :(得分:2)

假设您的数组基于此循环从1开始,按照您设置的方式执行此操作将是:

For j = 1 To 10
    if "condition" then
    ReDim Preserve similarValues(1 To j) 'reevaluates array from 1 to ubound + 1
    similarValues(j) = 'whatever
    End if
Next j

但是,这可能不起作用,因为你循环j,这将留下空数组值,在那里你的if条件不满足。我会:

Dim i As integer
i = 1
For j = 1 To 10
    if "condition" then
        ReDim Preserve similarValues(1 To i) 'reevaluates array from 1 to i
        similarValues(i) = 'whatever
        i = i + 1 'i is only increased when the if condition is met
    End if
Next j

这应该保持您的数组大小和其中的项目数量一致

编辑:抱歉,我没有看到这不是您正在创建的阵列,而是已存在的阵列。如果初始化,你可以使用LBound和UBound()来查找大小,如果它未初始化,你可以使用错误处理程序来初始化它:

On Error GoTo ErrHandler

ErrHandler:
    ReDim Preserve similarValues(1 To 1)
    'Statement to navigate back to loop

在这种情况下,您可以使用:

ComeBack:
On Error GoTo ErrHandler
For j = 1 To 10
    if "condition" then
    ReDim Preserve similarValues(1 To UBound(similarValues) + 1) 'reevaluates array from 1 to j
    similarValues(UBound(similarValues)) = 'whatever
    End if
Next j

ErrHandler:
    ReDim Preserve similarValues(1 To 1)
    GoTo ComeBack

另外,如果你知道它开始时未初始化,你可以在循环之前从1到1 ReDim以确保它被初始化