Why first letter in the first name deleting itself when typing the second letter; VBA 7?

31 Views Asked by At

This is the where we enter the value = txtSearchCenter

This is where the result will be = lstPersonnelSearch

    Option Compare Database
Private Sub txtSearchCriteria_KeyPress(KeyAscii As Integer)
    Dim vSearchString As String

    If KeyAscii = vbKeyBack Then
        ' Handle backspace separately
        If Len(Nz(Me.txtSearchCriteria.Value, "")) > 0 Then
            vSearchString = Left(Nz(Me.txtSearchCriteria.Value, ""), Len(Nz(Me.txtSearchCriteria.Value, "")) - 1)
        Else
            vSearchString = ""
        End If
    Else
        ' For other keys, including regular characters and Enter key
        vSearchString = Nz(Me.txtSearchCriteria.Value, "") & Chr(KeyAscii)
    End If

    Dim strSQL As String
    strSQL = "SELECT * FROM QrySearch WHERE FirstName Like '*" & vSearchString & "*'"
    
    Me.lstPersonnelSearch.RowSource = strSQL
    
    ' Optionally refresh the list box immediately
    ' Me.lstPersonnelSearch.Requery
    
    Me.Refresh
End Sub

This is the where we enter the value = txtSearchCenter image description hereriteria

This is where the result will be = lstPersonnelSearch

I have tried so many ways to display a query result in a form. The current problem I got is the first letter of a name is deleted when typing the second letter. First letter it filters all the name starts with F and when the second letter O is entered it deletes the F and filter the list box to people whose name starts with letter O. I dont know what is the problem. Please help !

1

There are 1 best solutions below

0
Jix Tang On

Thanks to @Andre. Below is the update code; Now its working fine.

Option Compare Database

Private Sub txtSearchCriteria_Change()
    Dim vSearchString As String

    vSearchString = Me.txtSearchCriteria.Text

    ' Set the filter criteria in the query
    Dim filterString As String
    filterString = "FirstName Like '*" & vSearchString & "*'"

    ' Update the RowSource of the list box
    Me.QrySearch.RowSource = "SELECT * FROM QryEmpSearch WHERE " & filterString
End Sub