问题描述:

My problem is that in VBA I'm not able to stop a user from leaving a textbox after entering a incorrect value. I have tried the .SetFocus however this still allows leave after entering a incorrect value.

Does anyone have a solution to this?

This is what I currently have:

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

I may want to add that this code all works correctly, the only problem is, it lets you leave the text box after you enter a incorrect value

网友答案:

Use the text box's Before Update event to check whether the value is valid. When invalid, Cancel the event and the cursor will remain in the text box.

Private Sub txtTimeOfDelivery_BeforeUpdate(Cancel As Integer)
    ' do your value checking and ...
    ' Cancel when invalid
    Cancel = True
End Sub
网友答案:

On the LostFocus event, you could re-set the focus to the textbox if the value is incorrect?

相关阅读:
Top