Filter Listbox By Textbox Contents (1 Viewer)

3link

Registered User.
Local time
Today, 03:45
Joined
Jun 1, 2012
Messages
12
So basically I want to type something into a textbox and have that automatically run a query in my listbox for like values.

This is the code I'm using.
txtProperty = Text box
lstSearchResults = List Box
Table = Table

Code:
Private Sub txtProperty_Change()
    On Error GoTo Err_txtProperty_Change
    Dim strSource As String
    strSource = "SELECT ID, List " & _
        "FROM Table " & _
        "Where ID Like '*" & Me.txtProperty.Text & "*' " _
    Me.lstSearchResults.RowSource = strSource

Exit_txtProperty_Change:
    Exit Sub
Err_txtProperty_Change:
    MsgBox Err.Number & " " & Err.Description
    Resume Exit_txtProperty_Change
End Sub

This code doesn't work. Whenever I try, nothing happens. I remember I've done this in the past and there's a trick to it, but I don't recall what that trick was. Anyone have any ideas what I'm missing?
 

JHB

Have been here a while
Local time
Today, 12:45
Joined
Jun 17, 2012
Messages
7,732
I think you need to requery the listbox after you set the rowsource.
But there are also some inconveniences in the code.

  • "Table" is a keyword in MS-Access and shouldn't be used as a name!
  • Why do you've "Text" in "Me.txtProperty.Text", why not just "Me.txtProperty"
  • Either you've made a typo or you've left some code lines out, then you've a "_" at the end of ""Where ID Like '*" & Me.txtProperty.Text & "*' " _ " and that will give you a compiler error.
  • "ID" is normally used for numbers so as pbaldy mention are you sure it contains text values?
Code:
Private Sub txtProperty_Change()
    On Error GoTo Err_txtProperty_Change
    Dim strSource As String
    strSource = "SELECT ID, List " & _
        "FROM Table " & _
        "Where ID Like '*" & Me.txtProperty & "*' "
    Me.lstSearchResults.RowSource = strSource
    Me.lstSearchResults.Requery
  
Exit_txtProperty_Change:
    Exit Sub
Err_txtProperty_Change:
    MsgBox Err.Number & " " & Err.Description
    Resume Exit_txtProperty_Change
End Sub
If ID is number, then:
Code:
Private Sub txtProperty_Change()
    On Error GoTo Err_txtProperty_Change
    Dim strSource As String
    strSource = "SELECT ID, List " & _
        "FROM Table " & _
        "Where ID Like *" & Me.txtProperty & "* "
    Me.lstSearchResults.RowSource = strSource
    Me.lstSearchResults.Requery
  
Exit_txtProperty_Change:
    Exit Sub
Err_txtProperty_Change:
    MsgBox Err.Number & " " & Err.Description
    Resume Exit_txtProperty_Change
End Sub
 

pbaldy

Wino Moderator
Staff member
Local time
Today, 03:45
Joined
Aug 30, 2003
Messages
36,130
I'll get out of the way. I've never needed to requery after setting a row source, and the need for the .Text property is apparent from the event. ;)
 

Users who are viewing this thread

Top Bottom