【问题标题】:Remove Listbox item if match not found in VBA如果在 VBA 中找不到匹配项,则删除列表框项
【发布时间】:2015-07-30 00:27:31
【问题描述】:

我正在编写 vba 代码,它将针对工作表中的整个列搜索所有列表框项。 如果在 Excel 工作表列中找不到列表框项目,我想从列表中删除该项目。我尝试了一些代码,它显示一些错误为“无法获取列表属性,无效的属性数组索引”。以下是我目前正在使用的代码。

Private Sub CommandButton1_Click()
    Dim itemExistResults As Boolean
    Dim myarray()
    Dim intItem As Long

    myarray = Application.Transpose(Sheet1.Range("a2:a1000"))

    For intItem = 0 To ListBox1.ListCount - 1
        If IsInArray(ListBox1.List(intItem), myarray) Then
        Else
            ListBox1.RemoveItem intItem
        End If
    Next

End Sub

Function IsInArray(stringToBeFound As String, arr As Variant) As Boolean
    IsInArray = UBound(Filter(arr, stringToBeFound)) > -1
End Function

知道我在这段代码中哪里错了。

【问题讨论】:

    标签: vba


    【解决方案1】:

    您应该从列表的最后一项迭代到第一项,因为删除项会改变它们的索引。

    尝试像这样改变你的循环:

        For intItem = ListBox1.ListCount - 1 To 0 Step -1
            If IsInArray(ListBox1.List(intItem), myarray) Then
            Else
                ListBox1.RemoveItem intItem
            End If
        Next
    

    我有一个与您的任务相关的提示,但与所描述的错误不完全一致。

    对于这种类型的任务,您应该使用Dictionary 类型的对象而不是遍历数组——这样会更有效。

    我已修改您的代码以使用字典。检查并比较每个解决方案完成此任务所需的时间 - 带有字典的解决方案应该快得多。如果您对此代码有任何疑问,请在 cmets 中告诉我。

    Private Sub CommandButton1_Click()
        Dim myArray As Variant
        Dim intItem As Long
        Dim dict As Object
        Dim i As Long
        Dim value As Variant
    
    
        '--- [Loading data into dictionary] ------------------------------------
        Set dict = VBA.CreateObject("Scripting.Dictionary")
        myArray = Sheet1.Range("A2:A1000")
    
        'Iterate through all the items in array and load them into dictionary.
        For i = LBound(myArray) To UBound(myArray)
    
            value = myArray(i, 1)
    
            If Not IsEmpty(value) Then
                If Not dict.exists(value) Then
                    Call dict.Add(value, 0)
                End If
            End If
        Next i
        '-----------------------------------------------------------------------
    
    
    
        '--- [Comparing ListBox with dictionary] -------------------------------
        With ListBox1
            For intItem = .ListCount - 1 To 0 Step -1
                value = .List(intItem)
    
                If Not dict.exists(value) Then
                    .RemoveItem intItem
                End If
    
            Next
        End With
        '-----------------------------------------------------------------------
    
    End Sub
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2018-04-15
      • 2017-12-26
      • 1970-01-01
      • 2020-09-29
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-01-16
      相关资源
      最近更新 更多