我的问题是,在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
我可能想补充一点,这段代码一切正常,唯一的问题是,它让你在输入错误值后离开文本框
答案 0 :(得分:3)
使用文本框的 Before Update 事件检查该值是否有效。无效时,Cancel
事件和光标将保留在文本框中。
Private Sub txtTimeOfDelivery_BeforeUpdate(Cancel As Integer)
' do your value checking and ...
' Cancel when invalid
Cancel = True
End Sub
答案 1 :(得分:0)
在LostFocus事件中,如果值不正确,您可以将焦点重新设置为文本框?