Filter Only matching results in ListBox Excel from TextBox text

微笑、不失礼 提交于 2020-01-06 06:29:40

问题


I have a user form with a textbox and a listbox. I would like a user to be able to enter text into the textbox, and have the listbox filter results based on their typing.

So far, I have managed to get the ListBox to highlight matching results in the list, but not filter out results that dont match. I have also run into the issue of my code not identifying multiple matching records, not sure what I need to add to get this to happen.

Private Sub TextBox3_Change()
        'searches ListBox3 for match and hightlights result. Need to filter results.
    Dim i As Long
    Dim sFind As String

    sFind = Me.TextBox3.Text

    If Len(sFind) = 0 Then
        Me.ListBox3.ListIndex = -1
        Me.ListBox3.TopIndex = 0
    Else
        For i = 0 To Me.ListBox3.ListCount - 1
            If UCase(Left(Me.ListBox3.List(i), Len(sFind))) = UCase(sFind) Then
                Me.ListBox3.TopIndex = i
                Me.ListBox3.ListIndex = i
                Exit For
            End If
        Next i
    End If
End Sub

回答1:


Try using this code that works when you exit textbox3, otherwise it will make some filtering while typing and can bring errors.

If the match is exact

Private Sub TextBox3_Exit(ByVal Cancel As MSForms.ReturnBoolean)
For i = ListBox1.ListCount - 1 To 0 Step -1
    If Not ListBox1.List(i) = TextBox3 Then ListBox1.RemoveItem (i)
Next i
End Sub

And the loop is made with a recursive loop, otherwise an error appear.

For partial matches

Private Sub TextBox3_Exit(ByVal Cancel As MSForms.ReturnBoolean)
For i = ListBox1.ListCount - 1 To 0 Step -1
    If InStr(1, ListBox1.List(i), TextBox3) = 0 Then ListBox1.RemoveItem (i)
Next i
End Sub

Found a better code to filter a listbox.



来源:https://stackoverflow.com/questions/46230496/filter-only-matching-results-in-listbox-excel-from-textbox-text

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!