我在连续表单的标题中有一个文本框控件。输入到文本框中的任何字符都用于构建和应用过滤字符串。应用过滤器后,使用set focus和selstart将焦点设置回文本框,以便用户可以添加更多字符。结果是在输入每个字符时过滤记录列表。
设置的过滤器代码由change事件上的文本框触发。代码将焦点移动到另一个控件然后返回,以便更新textbox.value属性(我尝试使用.text但仍然遇到其他焦点问题)。
记录过滤工作o.k.直到输入一个字符串,导致显示零记录。此时,设置Selstart属性的VBA行抛出“除非有焦点,否则无法设置控件的属性”错误。下面列出了代码行,TxtFilterString是文本框的名称,LengthOfText是一个整数,SetFormFilter是构建过滤器并应用它的子:
LengthOfText = Len(Me.TxtFilterString.Value)
SetFormFilter
Me.TxtFilterString.SetFocus
Me.TxtFilterString.SelStart = LengthOfText
当没有要显示的记录时,Me.TxtFilterString.SetFocus行似乎失败,这导致以下行抛出错误,尽管控件在标题部分中可见。
有什么想法?我错过了什么?
感谢阅读。 垫木
答案 0 :(得分:0)
我假设你有列表框显示你的查询结果 如果在列表框中显示0条记录时出现错误,那么您是否可以对列表框结果进行简单检查,而不会运行错误行?
if listbox.listcount >0 then
Me.TxtFilterString.SelStart = LengthOfText
endif
答案 1 :(得分:0)
我不知道为什么会出现这个问题,但我的解决方案是如果记录集为空或者问题的文本框包含null,如果使用delete键删除了内容,则似乎不会执行代码行。我的变更子在这里:
Private Sub TxtFilterString_Change()
' Call sub that sets the form filter to value entered in text box
Dim LengthOfText As Integer
On Error GoTo ErrHandler
Me.CmdResetSearch.SetFocus ' move the focus away to update the value prop, as the text prop has focus issues
Me.TxtFilterString.SetFocus
SetFormFilter ' build and set the continuous forms filter string
' The following if block is to overcome a bug where Access does not allow the
' set focus property of the text field to be set when there are no records to display
' The result is that the filter string that returns zero records becomes highlighted
' allowing it to be overwritten.
' The IsNull clause is required if the user used delete to remove the text in the text box
If Me.Recordset.RecordCount = 0 Or IsNull(Me.TxtFilterString) Then
' There are no records or the user has deleted in the field (causing a Null to be enetered)
Me.TxtFilterString.SetFocus
Else
' There are records and there is text in the text box so set focus and caret position
Me.TxtFilterString.SetFocus
Me.TxtFilterString.SelStart = Len(Me.TxtFilterString.Value)
End If
Exit Sub
ErrHandler:
MsgBox "An error in TxtFilterString_change : " & Err.Description, vbExclamation
Exit Sub
End Sub