arrays - 无法从数组中删除不需要的项目

标签 arrays excel vba

我正在尝试找出从列表中剔除不需要的项目的任何方法。例如,我希望摆脱 4790从列表中删除,因为它们不符合条件。我用过Delete在脚本中这绝对不是正确的关键字。但是,将其视为占位符。

我试过:

Sub DeleteItemConditionally()
    Dim numList As Variant, elem As Variant

    numList = Array("12", "47", "90", "15", "37")

    Debug.Print UBound(numList) - LBound(numList) + 1

    For Each elem In numList
        If elem >= 40 Then
            Delete elem
        End If
    Next elem

    Debug.Print UBound(numList) - LBound(numList) + 1
End Sub

预期结果:
First print : 5 (already getting it)
Second print: 3 (want to achieve it)

最佳答案

向数组添加和删除其他元素相当慢。并使用 Redim 更改数组的维度是 VBA 中最慢的操作之一。无论如何,如果我们谈论的案例数量相当多,那么速度还可以:

Option Explicit

Sub DeleteItemConditionally()

    Dim numList As Variant
    numList = Array(12, 47, 90, 15, 3)

    Dim newElements() As Variant
    Dim firstElement As Boolean: firstElement = True
    Dim i As Long

    For i = LBound(numList) To UBound(numList)
        If numList(i) <= 40 Then
            If firstElement Then
                ReDim Preserve newElements(0)
                firstElement = False
            Else
                ReDim Preserve newElements(UBound(newElements) + 1)
            End If

            newElements(UBound(newElements)) = numList(i)

        End If
    Next

    Dim element As Variant
    For Each element In newElements
        Debug.Print element
    Next

End Sub

收藏或 System.Collections.ArrayList如下例所示,优化和速度会更快(但如果数据不超过几百个项目,仍然会稍微不可见)。此外,可以对集合进行相当快的排序,然后任务的速度会更好:
Sub TestMyCollection()

    Dim myList As Object
    Set myList = CreateObject("System.Collections.ArrayList")

    With myList
        .Add 12
        .Add 47
        .Add 90
        .Add 15
        .Add 3
    End With

    myList.Sort
    Dim i As Long
    For i = myList.Count - 1 To 0 Step -1
        If Not myList.Item(i) <= 40 Then
            myList.RemoveAt i
        End If
    Next i

    Dim element As Variant
    For Each element In myList
        Debug.Print element
    Next

End Sub

此外,为了提高性能并更好地使用 .Sort()在第一个数字之后,大于 40 的 For i = myList.Count - 1 To 0 Step -1可以退出。

关于arrays - 无法从数组中删除不需要的项目,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57761883/

相关文章:

c - 在C中为结构指针数组成员分配地址

vba - 如何在VBA中结束无限 "change"循环

VBA,日期格式问题

vba - 从不同工作簿中的单元格中提取超链接目标

vba - 打开工作簿的上次修改日期

VBA 转到最后一个空行

java - 将数组排序为三个不同的 ArrayLinearList

c++ - 条件宏或扩展模板

c++ - 静态二维数组

excel - VBA 测试单元格是否在范围内