Een listbox dynamisch filteren

Een listbox op een userform dynamisch filteren.

Ten eerste, sla op de toetscombo Alt+F11 om in de VBE te belanden. Voeg een  userform toe  en gooi er een textbox, een listbox en een knop op.

Ten tweede, op “Sheet2” in je werkmap zet je wat data bijvoorbeeld namen en adressen. Ik heb het mezelf gemakkelijk gemaakt en die Noordenwind database van MS gebruikt zoals je kunt zien …

Download een voorbeeld van de Noordenwind database.

Sub Filter_Listbox()
    UserForm1.Show
End Sub

Deze code voeg je in de userform module in:

Private Sub TextBox1_Change()
    With Worksheets("Sheet2")

        'Read TextBox
        strLetter = Me.TextBox1.Text

        'Clear ListBox
        Me.ListBox1.Clear

        'If filtermode is on show me all data from Sheet2
        If .FilterMode Then .ShowAllData

        'Read column A of the original list
        vList = Range("A2", Cells(Rows.Count, _
            1).End(xlUp)).Value

        'Convert it to a 1D array
        vList = Application.Transpose(vList)
        'Filter it using the Filter function,
        'available in VB6 (meaning from Excel 2000 and above).
        vList = Filter(SourceArray:=vList, Match:=strLetter, _
            Include:=True, Compare:=vbTextCompare)

        'Send it to the listbox
        Me.ListBox1.List = vList
    End With
End Sub

Private Sub UserForm_Initialize()
    With Worksheets("Sheet2")

        'Clear ListBox
        Me.ListBox1.Clear

        'If filtermode is on show me all data
        If .FilterMode Then .ShowAllData
        
        'Read column A of the original list
        'and sent it to the listbox
        'No Filtering necessary
        Me.ListBox1.List = Range("A2", Cells(Rows.Count, _
            1).End(xlUp)).Value

        'Set Focus to TextBox
        Me.TextBox1.SetFocus
    End With
End Sub

Private Sub CommandButton1_Click()
    MsgBox ListBox1.Value
    'Unload the userform
    Unload Me
End Sub

Leave a Reply

Your email address will not be published. Required fields are marked *