You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

SetFocus方法未聚焦目标文本框tbxStartTime问题求助

解决Access表单控件验证后焦点跳转异常问题

你的代码存在几处关键问题,再加上Access表单的默认事件行为,导致焦点无法正确停留在tbxStartTime文本框:

问题拆解

  • 变量未定义与错误屏蔽:代码里的dTime未定义,On Error Resume Next会掩盖这个错误,让Format语句直接失效;另外用DateValue处理时间输入不合适,应该用TimeValue来解析时间值。
  • Text属性使用错误:tbxStartTime.Text仅在控件获得焦点时才能访问,而AfterUpdate事件触发时控件已经失去焦点,直接调用会报错(被错误屏蔽语句掩盖),应该改用Value属性操作内容。
  • Access默认焦点行为:AfterUpdate事件执行完毕后,Access会自动将焦点移到Tab键顺序的下一个控件,即使你调用了SetFocus,默认行为也会覆盖这个操作。

方案1:改用BeforeUpdate事件(推荐)

BeforeUpdate是专门用于输入验证的事件,在数据更新前触发,通过Cancel=True可以阻止更新,同时让焦点保持在当前控件,逻辑更清晰:

Private Sub tbxStartTime_BeforeUpdate(Cancel As Integer)
    Dim formattedTime As String
    
    ' 验证空值
    If Trim(tbxStartTime.Value) = "" Then
        MsgBox "Please enter the Time in the correct format"
        tbxStartTime.Value = ""
        Cancel = True ' 取消更新,锁定焦点在当前控件
        Exit Sub
    End If
    
    ' 验证是否为有效时间格式
    If Not IsDate(tbxStartTime.Value) Then
        MsgBox "Please enter the Time in the correct format"
        tbxStartTime.Value = ""
        Cancel = True
        Exit Sub
    End If
    
    ' 验证格式是否符合要求
    formattedTime = Format(TimeValue(tbxStartTime.Value), "h:mm am/pm")
    If tbxStartTime.Value <> formattedTime Then
        MsgBox "Please enter the Time in the correct format"
        tbxStartTime.Value = ""
        Cancel = True
        Exit Sub
    End If
    
    ' 验证通过后格式化显示
    tbxStartTime.Value = formattedTime
End Sub

方案2:修复原AfterUpdate事件

如果坚持使用AfterUpdate,需要修复代码错误,并通过两次设置焦点+DoEvents来覆盖Access的默认焦点行为:

Private Sub tbxStartTime_AfterUpdate()
    Dim ckTime As Date
    Dim formattedTime As String
    
    ' 移除错误屏蔽,避免隐藏问题
    On Error GoTo ErrorHandler
    
    ' 验证空值
    If Trim(tbxStartTime.Value) = "" Then
        GoTo InvalidInput
    End If
    
    ' 验证是否为有效时间
    If Not IsDate(tbxStartTime.Value) Then
        GoTo InvalidInput
    End If
    
    ' 转换为时间并格式化
    ckTime = TimeValue(tbxStartTime.Value)
    formattedTime = Format(ckTime, "h:mm am/pm")
    
    ' 验证格式匹配
    If tbxStartTime.Value <> formattedTime Then
        GoTo InvalidInput
    End If
    
    ' 格式化显示
    tbxStartTime.Value = formattedTime
    Exit Sub
    
InvalidInput:
    MsgBox "Please enter the Time in the correct format"
    tbxStartTime.Value = ""
    tbxStartTime.SetFocus
    DoEvents ' 处理事件队列,确保焦点设置生效
    tbxStartTime.SetFocus ' 再次设置焦点,覆盖默认跳转行为
    Exit Sub
    
ErrorHandler:
    MsgBox "Error: " & Err.Description
    tbxStartTime.Value = ""
    tbxStartTime.SetFocus
End Sub

内容的提问来源于stack exchange,提问作者Les Murrell

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.27 17:56:19