【问题标题】:How to set focus following setting Form Filter that returns zero records如何在设置返回零记录的表单过滤器后设置焦点
【发布时间】:2015-04-29 12:29:33
【问题描述】:

我在连续表单的标题中有一个文本框控件。输入的字符用于构建和应用过滤字符串。应用过滤器后,使用 set focus 和 selstart 将焦点设置回文本框,以便用户能够添加更多字符。结果是在输入每个字符时过滤记录列表。

设置过滤器代码由文本框 on change 事件触发。代码将焦点移到另一个控件,然后返回,以便更新 textbox.value 属性(我尝试使用 .text 但一直遇到其他焦点问题)。

记录过滤一直有效,直到输入导致显示零记录的字符串。
此时设置 Selstart 属性的 VBA 行抛出

"除非控件具有焦点,否则不能设置控件的属性"

代码行如下,TxtFilterString 是文本框的名称,LengthOfText 是整数,SetFormFilter 是构建过滤器并应用它的子:

LengthOfText = Len(Me.TxtFilterString.Value)

SetFormFilter

Me.TxtFilterString.SetFocus
Me.TxtFilterString.SelStart = LengthOfText

当没有要显示的记录时,Me.TxtFilterString.SetFocus 行似乎失败,这会导致以下行引发错误,尽管该控件在标题部分可见。

【问题讨论】:

    标签: vba ms-access ms-access-2007 setfocus


    【解决方案1】:

    我假设您有显示查询结果的列表框。
    如果在列表框中显示 0 条记录时出错,那么您能否不对列表框结果进行简单检查,以确保不会运行错误行?

    if listbox.listcount >0 then
      Me.TxtFilterString.SelStart = LengthOfText
    endif
    

    【讨论】:

    • 对不起,如果我没有说清楚。输入到未绑定文本框中的文本用于创建过滤子句,然后将其应用于表单。表单显示连续的记录,当没有要显示的记录时会出现问题。但是,我有一个与您的建议相似的解决方法,我将发布作为答案。
    【解决方案2】:

    我不知道为什么会出现问题,但我的解决方案是如果记录集为空或相关文本框包含 null 则不执行代码行,如果使用删除键删除内容似乎会发生这种情况。我的变更子在这里:

    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
    

    【讨论】:

      猜你喜欢
      • 2017-04-07
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-10-31
      • 2014-07-12
      相关资源
      最近更新 更多