To "automatically" upshift data, code the keypress event:
Sub Text1_KeyPress (KeyAscii As Integer)
KeyAscii = Ascii(UCase(Char(Keyascii)))
End Sub
To limit data entered to very specific values, code the keypress event:
'this is brute-force method of limiting to number but mask is easier.
Sub Text1_KeyPress (KeyAscii As Integer)
If KeyAscii = 8 Then 'Allow BACKSPACE through
Exit Sub
End If
'Only digits are valid characters.
If Chr(KeyAscii) < "0" Or Chr(KeyAscii) > "9" Then
KeyAscii = 0 'Set character to null if out of range
Beep
End If
End Sub
To Give User Feedback when they violate mask conditions, code the ValidationError event:
Sub mskID_ValidationError (InvalidText As String, StartPosition As Integer)
'Check for too many digits error. o/w user is trying to enter non-numeric.
If StartPosition = mskID.MaxLength Then
lblError.Caption = "Limit 6 digits"
Else
lblError.Caption = "Digits only"
End If
End Sub
LostFocus Code that Returns Focus to this Field and Avoids Infinite Loop
Dim ValidationInProgress as Boolean (available to all controls on Form)
Private Sub txtFirstName_LostFocus()
If Not (ValidationInProgress) Then 'ok to validate
If txtFirstName.Text = "" Then
ValidationInProgress = True
txtFirstName.SetFocus
lblError.Caption = "First Name is required."
DoEvents
ValidationInProgress = False
End If
End If
End Sub
Note: the above example is bad for usability because they do mandatory field validation at the field (rather than Form) level. How does the user "get out" if he doesn't know the value?
Validate in LostFocus, only if data is changed
Declare "IFlag" as Integer in Form’s general declaration (can reuse this variable across both events and controls).
- In GetFocus, set IFlag = 0
- In Change, set IFlag = 1
- In LostFocus, "If IFlag = 1 Then … code for when item is changed.
** you've already lost focus by the time this event fires so you'd have to set focus back to get the user to fix it. See use of a global like "validation-in-progress" above to ensure you don't get infinite loops resetting focus.
Monitor for hot-key
code KeyPress event of the Form (instead of coding it for every control on the Form)
Private Sub Form_KeyDown(KeyCode As Integer, Shift As Integer)
If KeyCode = vbKeyF2 Then
MsgBox "You Pressed F2!"
End If
End Sub
Note: the KeyPreview property determines whether Form sees keystrokes before its controls
|