如何阻止用户离开文本框?

内容来源于 Stack Overflow,并遵循CC BY-SA 3.0许可协议进行翻译与使用

  • 回答 (2)
  • 关注 (0)
  • 查看 (25)

我的问题是,在VBA中,我无法阻止用户在输入错误值后离开文本框。我已经尝试过.SetFocus但是这仍然允许在输入不正确的值后离开。

有人有解决方案吗?

这就是我目前的代码:

Private Sub txtTimeOfDelivery_Exit(Cancel As Integer)
Select Case comboDriverID.Value
    Case "1"
If txtTimeOfDelivery < "17:00:00" Or txtTimeOfDelivery > "22:00:00" Then
MsgBox "Warning, the selected delivery time is not within Johns working hours"
txtTimeOfDelivery.SetFocus
Else
Exit Sub
End If
    Case "2"
     If txtTimeOfDelivery < "17:00:00" Or txtTimeOfDelivery > "22:00:00" Then
MsgBox "Warning, the selected delivery time is not within Harrys working hours"
txtTimeOfDelivery.SetFocus
Else
Exit Sub
End If
Case "3"
     If txtTimeOfDelivery < "17:00:00" Or txtTimeOfDelivery > "22:00:00" Then
MsgBox "Warning, the selected delivery time is not within Shaws working hours"
txtTimeOfDelivery.SetFocus
Else
Exit Sub
End If
Case "4"
     If txtTimeOfDelivery < "17:00:00" Or txtTimeOfDelivery > "22:00:00" Then
MsgBox "Warning, the selected delivery time is not within Patricks working hours"
txtTimeOfDelivery.SetFocus
Else
Exit Sub
End If
Case "5"
     If txtTimeOfDelivery < "17:00:00" Or txtTimeOfDelivery > "22:00:00" Then
MsgBox "Warning, the selected delivery time is not within Pauls working hours"
txtTimeOfDelivery.SetFocus
Else
Exit Sub
End If
Case Else
     If txtTimeOfDelivery < "17:00:00" Or txtTimeOfDelivery > "22:00:00" Then
MsgBox "Please carefully check the drivers working hours"
txtTimeOfDelivery.SetFocus
Else
Exit Sub
End If
    End Select

我可能想补充一点,这段代码都能正常工作,唯一的问题是,它允许你输入一个不正确的值后离开文本框。

提问于
用户回答回答于

使用文本框的Before Update事件检查值是否有效。无效时,Cancel事件和光标将保留在文本框中。

Private Sub txtTimeOfDelivery_BeforeUpdate(Cancel As Integer)
    ' do your value checking and ...
    ' Cancel when invalid
    Cancel = True
End Sub
用户回答回答于

在LostFocus事件上,如果值不正确,可以将焦点重新设置为TextBox。

扫码关注云+社区

领取腾讯云代金券