为什么在输入第二个字母时,名字中的第一个字母会自动删除; VBA 7?

问题描述 投票:0回答:1

这是我们输入值= txtSearchCenter的地方

这就是结果 = 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

这是我们输入值的地方= txtSearchCriteria

这就是结果 = lstPersonnelSearch

我尝试了很多方法来将查询结果显示在表单中。我当前遇到的问题是输入第二个字母时名称的第一个字母被删除。第一个字母它会过滤所有以 F 开头的名字,当输入第二个字母 O 时,它会删除 F 并将列表框过滤到名字以字母 O 开头的人。我不知道问题是什么。请帮忙!

ms-access ms-access-2016 vba7 ms-forms
1个回答
0
投票

感谢@Andre。以下是更新代码;现在工作正常了。

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
© www.soinside.com 2019 - 2024. All rights reserved.