wohoohi
wohoohi

Reputation: 5

'Search as you type' with KeyPress Event

I have a form to execute queries. There is a search bar to search for Items (Vendors) from a local Table you could select and which the Endresults would be based on.

I have the following Items:

I have a button to show search results.

Private Sub bt_vendor_search_Click()
    Dim strSearchSQL As String
    
    strSearchSQL = "SELECT Vendor, [Vendor Name] FROM vend_data WHERE " & _
      "Len(vend_data.Vendor) = 6 And ([Vendor Name] LIKE '*" & Me.txt_Vendor_Search & _
      "*' OR Vendor LIKE ""*" & Me.txt_Vendor_Search & "*"")"
    'Update the Row Source of the ListBox
    Me.ltVendorSearchResults.RowSource = strSearchSQL
    Me.ltVendorSearchResults.Requery

End Sub

To implement a live search, I select the KeyPress Event of the TextBox:

Private Sub txt_Vendor_Search_KeyPress(KeyAscii As Integer)  
    bt_vendor_search_Click
End Sub

With the debugger I found that the KeyPress event is triggered every time I type something. The AfterUpdate Event of the TextBox also executes the procedure of the button.

It is not super important, as I can press the button or Enter, but it would be a fancy addition to my form.

Upvotes: 0

Views: 1172

Answers (1)

AHeyne
AHeyne

Reputation: 3455

Two things:

  1. Use the On Change event (txt_Vendor_Search_Change()) instead of the KeyPress event.

  2. Use the Text property (Me.txt_Vendor_Search.Text) instead of the Value property (Me.txt_Vendor_Search uses the default property and that is Value).

Then it should work.

Upvotes: 2

Related Questions