简体   繁体   中英

Filter subform based on what is typed in a textbox on the subform

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...LI 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!

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM