Listbox1 包含来自 listbox2 的文本-> 删除项

Listbox1 Contains text from listbox2-> delete item

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

我需要检查 Listbox1 是否包含 Listbox2 中的列表项,如果包含,则删除 Listbox1 中包含 Listbox2 中的项的项。 例如列表框 1 中的项目 "purple monkey" 包含 "monkey"(列表框 2 中的项目),因此我需要删除整个项目 "purple monkey".

有人可以帮我吗?

我使用以下代码创建主列表(关键字)并初始化用户窗体。此外,我创建了一个文本框,用户可以在其中输入项目并将它们添加到 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 项目(不一定等于它们)的关键字。

假设您的用户窗体上有一个命令按钮 (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