不要使用该KeyPress事件,您将无法从事件处理程序本身中轻松地重建实际输入数据(触发事件时,刚刚按下的键尚未添加到文本框的文本中,这意味着你总是缺少最后一次击键)。
相反,使用KeyDown事件,并使用文本框的.Text属性而不是.Value.
.Value仅在焦点离开框后设置。
因此,您的代码可以简单地重写为(确保您的 KeyDown 事件设置在表单上的文本框事件中):
Private Sub TxtVendorSearch_KeyDown(KeyCode As Integer, Shift As Integer)
' If there is no filter criteria, disable filtering '
If Len(Trim(TxtVendorSearch.Text)) = 0 Then
subOrderDS1.Form.FilterOn = False
Exit Sub
End If
' Do nothing if user hits RETURN or TAB '
If KeyAscii < 32 Then
KeyCode = 0
Exit Sub
End If
Dim str1 As String
str1 = "[VendorID] LIKE '*" & Trim$(TxtVendorSearch.Text) & "*'"
subOrderDS1.Form.Filter = str1
subOrderDS1.Form.FilterOn = True
End Sub
我曾经Trim()删除用户可能键入的任何前导和尾随空格。
最后一件事:您不需要在表单代码本身中使用Me.或使用。
如果你这样做并没有什么坏处,但它会使事情变得不那么清晰,而无需向代码添加任何内容。Me!