Or you can put in some code in either the Change() event or the Validate() event.
The change event fires for each character the user enters, the validate event will fire before the TextBox looses focus. If using the validate you would go
Code:
Private Sub Text1_Validate(Cancel As Boolean)
If Val(Text1.Text) > MaxVal Then
MsgBox "Value exceeds maximum!"
Cancel = True
End If
End Sub
Setting Cancel to true will make the focus stay in Text1 to allow for editing the value.
The Validate() fires when the user attempts to go to another TextBox or Button, to continue his input. That means the user cannot leave the TextBox until the value is approved.
You could put a similar code (without the Cancel, though) int the Change() event, but this has some disadvantages.
Code:
Private Sub Text1_Change()
If Val(Text1.Text) > MaxVal Then
MsgBox "Value exceeds maximum!"
End If
End Sub
This fires the messagebox as soon as the entered value exceeds MaxVal, but after clicking away the messagebox the user can gladly continue going on to another input field, leaving the wrong value where it is.
For that purpose VB objects provide the Validate() event (as I stated before), which happens BEFORE the LostFocus().
The advantage is, if your validate routine finds the user input unsatisfying, it can set the Cancel parameter and AVOID the control to loose focus.
Bookmarks