Filter subform based on what is typed in a textbox on the subform
-
30-09-2019 - |
Question
I'm trying to filter the records shown on a subform based on what is typed in a textbox on the subform. The subform is called Users, and it is on the Group form. On the Users subform there is a textbox called txtFilter. If I type "W" in txtFilter, I want to show only records in which the User's lastName or userName begins with a "W". As I continue typing W...A...L I want only Users whose lastName or UserName begin with "Wal" to show up.
I have some vague idea that I have to use either the recordset property or the subform's serverFilter to do this, but I'm really at a loss as to what to do. Please help me!
Solution
Private Sub txtFilter_Change()
If Nz(Me.txtFilter.Text, "") = "" Then
Me.FilterOn = False
Me.txtFilter.SetFocus
Exit Sub
End If
Me.Filter = "lastName like '" + Me.txtFilter.Text + "%' or userName like '" & _
Me.txtFilter.Text + "%'"
Me.FilterOn = True
Me.txtFilter.SetFocus
Me.txtFilter.SelStart = Len(Nz(Me.txtFilter.Text, "")) + 1
End Sub
OTHER TIPS
Quick update to @dmr response for Access 2013:
- Change "%' to "*' - Access uses the asterisk for wildcard. Might want to add it before the text, in addition to after.
- You'll want to turn ON AllowAdditions in the form properties, or you'll have focus errors when your filter returns zero hits.
- This code will trim whitespaces, which makes it impossible to add spaces to your search (since you can't type 'two words' without first typing 'two ').
Modified response:
Private Sub txtFilter_Change()
Dim search_text As String
search_text = Me.txtFilter
If Nz(Me.txtFilter.Text, "") = "" Then
Me.FilterOn = False
Me.txtFilter.SetFocus
Exit Sub
End If
Me.Filter = "lastName like '*" + Me.txtFilter.Text + "*' or userName like '*" & _
Me.txtFilter.Text + "*'"
Me.FilterOn = True
Me.txtFilter.SetFocus
Me.txtFilter.Value = search_text
Me.txtFilter.SelStart = Len(Nz(Me.txtFilter.Text, "")) + 1
End Sub
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow