【问题标题】:Listbox1 Contains text from listbox2-> delete itemListbox1 包含来自 listbox2 的文本-> 删除项目
【发布时间】:2018-09-24 16:39:15
【问题描述】:

我有一个带有两个列表框的 VBA 用户窗体。我正在努力进行以下操作:

我需要检查 Listbox1 是否包含 Listbox2 中的列表项,如果包含,则删除 Listbox1 中包含 Listbox2 中的项的项。 例如listbox1中的“紫猴”项包含“猴子”(listbox2中的项),因此我需要删除整个“紫猴”项。

有人可以帮我吗?

我使用以下代码创建主列表(关键字)并初始化用户表单。此外,我创建了一个文本框,用户在其中输入项目并将它们添加到 Listbox2。此代码运行良好:

Private Sub UserForm_Initialize()

    Application.Visible = False

    Keywords.SetFocus
    TextBox2.Value = NegKeyList.ListCount & "negative keys"

    Dim mycollection As Collection, cell As Range

    On Error Resume Next

    Set mycollection = New Collection

    With Keywords

        .Clear

        For Each cell In Worksheets("Rawdata").Range("A3:A" & Cells(Rows.Count, 1).End(xlUp).Row)
            If Len(cell) <> 0 Then
                Err.Clear

                mycollection.Add cell.Value, cell.Value
                If Err.Number = 0 Then .AddItem cell.Value

            End If
        Next cell

    End With

    MsgBox mycollection.Count & "added to the list"

    If Keywords.ListCount > 0 Then
        TextBox1.Value = Keywords.ListCount & " keys"
    End If

End Sub

我现在需要创建另一个功能,用户可以按下按钮并删除所有包含 ListBox2 项的关键字(不一定等于它们)。

【问题讨论】:

  • 如果您已经有一些代码,您能否包括您尝试过的内容以及遇到的问题?如果没有,我建议查看 InStr() 和 ListBox 的 .Add.Remove 方法.....
  • 您需要遍历ListBox1,然后为ListBox2 嵌套另一个循环,并查看索引值是否相等(If ListBox1(i) = ListBox2(j) Then ListBox.RemoveItem i
  • 谢谢。我可以执行循环来比较列表并删除重复项,但我需要确保 Listbox1 中包含 Listbox2 中不完全相同的项目(文本)的项目被删除。
  • Mistella,我已经添加了代码,但这是我所拥有的。我无法理解如何使用 .Add 和 .Remove 来实现我在问题结尾提到的 .contain 功能。你能给我一个想法吗?

标签: vba excel listbox userform


【解决方案1】:

假设您的用户窗体上有一个命令按钮 (CommandButton1),您可以将代码放在 CommandButton1_Click() 事件中。由于某些项目可能会从 ListBox1 中删除,counter1 需要从最大值步长到最小值,以避免计数器的任何数组索引问题变得大于最大索引。

Dim counter1 as Long
Dim counter2 as Long

For counter1 = ListBox1.ListCount - 1 to 0 Step -1 'Indexes are 0-based, so max index is count - 1
    For counter2 = 0 to ListBox2.ListCount - 1
        If InStr(1, ListBox1.List(counter1), ListBox2.List(counter2)) > 0 Then 'InStr returns 0 when there's no match
            ListBox1.RemoveItem counter1
            Exit For 'Skip any more compares for the deleted Item
        End If
    Next counter2
Next counter1

【讨论】:

  • Mistella,我正在尝试使用代码,但它给了我 Listbox1(counter1) 上的类型不匹配错误。
  • @Garuzz 抱歉,请尝试更新版本。我将其更改为ListBox1.List(counter1),并将其更新为ListBox2
  • 是的!非常感谢!有效!!!只需将 Listbox2.Count 更正为 Listbox2.Listcount。
  • @Garuzz 请导航到该解决方案左侧的复选框,如果这对您有用,请接受该解决方案!
  • 清晰高效+1)。 放大说明:AddItem 方法不同(最好使用更快的数组!)RemoveItem 方法也适用于超过 10 个列表列。
猜你喜欢
  • 2019-12-16
  • 1970-01-01
  • 1970-01-01
  • 2021-09-02
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多