Avatar of Massimo Scola
Massimo Scola
Flag for Switzerland

asked on 

Excel VBA: Real-Time Search or Filtering in Listbox

I have a listbox with many records and I would like to have the ability to search inside the listbox.

The Listbox has several columns: Column 1 is the CustomerID, column 2 is the name and so on.

The following code searches inside the listbox, but only in the first column - which is the ID.
How do I change the code so that it searches inside the second column?
Private Sub txtSearch_Change()
  Dim strText As String
  Dim i As Long
  strText = LCase(txtSearch.Text)
  With ListBox1
    For i = 0 To .ListCount - 1
      If LCase(Left$(.List(i), Len(strText))) = strText Then Exit For
    Next i
    If i = .ListCount Then
      ' No matching item was found, select nothing
      .ListIndex = -1
      ' A match was found, select it
      .ListIndex = i
    End If
  End With
End Sub

Open in new window

Is it also possible to filter the listbox as I type?

Microsoft ExcelVBAMicrosoft OfficeVisual Basic Classic

Avatar of undefined
Last Comment

8/22/2022 - Mon