VBA realtime filter Listbox through Textbox

对着背影说爱祢 提交于 2019-12-05 20:05:24

Finally I could come out with something!

Sub Filter_Change()

Dim i As Long
Dim Str As String

Str = Me.Filter.Text

Me.RefreshList

If Not Str = "" Then
    With Me.ListBox1

        For i = .ListCount - 1 To 0 Step -1
            If InStr(1, LCase(.List(i, 0)), LCase(Str)) = 0 And InStr(1, LCase(.List(i, 1)), LCase(Str)) = 0 And _
              InStr(1, LCase(.List(i, 2)), LCase(Str)) = 0 And InStr(1, LCase(.List(i, 3)), LCase(Str)) = 0 Then

                .RemoveItem i

            End If
        Next i

    End With
End If

End Sub

I know, the answer is couple of years old...

But I thought I'd share solution that works the best for me, because the filter is blazing fast even when there are thousands of items in the list. It is not without a "catch", though: it uses a Dictionary object

Option Explicit
Dim myDictionary As Scripting.Dictionary

Private Sub fillListbox()
    Dim iii As Integer

    Set myDictionary = New Scripting.Dictionary

    ' this, here, is just a "draft" of a possible loop 
    ' for filling in the dictionary
    For iii = 1 To RANGE_END
        If Not myDictionary.Exists(UNIQUE_VALUE) Then
            myDictionary.Add INDEX, VALUE
        End If
    Next

    myListbox.List = myDictionary .Items

End Sub

Private Sub textboxSearch_Change()
    Dim Keys As Variant

    Keys = myDictionary .Items
    myListbox.List = Filter(Keys, textboxSearch.Text, True, vbTextCompare)

End Sub

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