Limit input in textbox that allows only digits, backspaces and one decimal point to be entered .
Method 1 using keypress event:
Private sub Text1_KeyPress(KeyAscii As Integer)
Const Numbers$ = "0123456789." 'Permitted values in Textbox
If KeyAscii <> 8 Then 'Ascii for BackSpace 8
If InStr(Numbers, Chr(KeyAscii)) = 0 Then 'If false, keypressed is suppressed
MsgBox "error"
KeyAscii = 0
Exit Sub
end If
end If
End Sub
------------------------------
Method 2 using function-call:
Function LimitTextInput(source) as String
Const Numbers$ = "0123456789."
If source <> 8 Then 'backspace is 8
If InStr(Numbers, Chr(source)) = 0 Then
LimitTextInput = 0
exit Function
end If
end If
LimitTextInput = source
End Function
Private Sub Text1_KeyPress(KeyAscii As Integer)
KeyAscii = LimitTextInput(KeyAscii) 'Calling LimitTextInput function
End Sub
------------------------------
Method 3 simple keypress event:
Private sub Text1_KeyPress(KeyAscii As Integer)
If KeyAscii > 65 And KeyAscii < 123 Then
KeyAscii = 0
End If
End if
-------------------------------
Method 4 using Validate event:
Private Sub Text1_Validate(Cancel As Boolean)
Cancel = IIF(Not IsNumeric(Text1), True, False)
If Cancel then
Msgbox "Enter Numeric Value only!", VbInformation, "Entry Error"
With Text1
. text = " "
.SetFocus
End With
End if
End Sub
In this event, the user can not exit textbox unless inputting Numericvalue and also all other controls in the Form will be disabled.
Method 4 One More Example
Private Sub Text1_Validate(Cancel As Boolean)
Cancel = Not IsDate(Text1.Text) Or Text1.Text <> Format(Text1.Text, "hh:mm:ss")
If Cancel Then
With lblSetTime
.Caption = "Set Time in 24hr Format!"
.ForeColor = vbRed
End With
Text1.Text = ""
Text1.SetFocus
CmdStart.Enabled = False
Else
CmdStart.Enabled = True
End If
End Sub
In the above example, user is forced to enter time in "hh:mm:ss" format only for use in setting Alarm Time. Entries of anything else will be curbed by Validate event. If input is in "hh:mm:ss" format, then only the CmdStartButton will be enabled to permit user to click it.
__________________________________End__________________________________