Hi,
Can anyone tell me how to restrict user to enter ONLY LETTERS & NUMBERS into a TextBox?
Thanks.
Printable View
Hi,
Can anyone tell me how to restrict user to enter ONLY LETTERS & NUMBERS into a TextBox?
Thanks.
You could code something like the following in the textbox's KeyPress event:
Code:Private Sub Text1_KeyPress(KeyAscii As Integer)
Dim strChar As String
' Accept the key if its a "control character" ...
If KeyAscii < 32 Then Exit Sub
strChar = Chr$(KeyAscii)
' Accept the key if it's numeric ...
If strChar >= "0" And strChar <= "9" Then Exit Sub
strChar = UCase$(strChar)
' Accept the key if it's alpha ...
If strChar >= "A" And strChar <= "Z" Then Exit Sub
' Otherwise, reject the key ...
KeyAscii = 0
End Sub
Thanks for your reply, but I'm not sure why did you include this piece of code:
' Accept the key if its a "control character" ...
If KeyAscii < 32 Then Exit Sub
Thanks.
you may want to backspace...keyascii = 8
that is a control key
ASCII codes from 0 to 31 are considered control characters (as Wayne pointed out, #8 is backspace). Others in this group include the navigation keys such as left arrow and right arrow. In the KeyPress event, you do not want to restrict the user from entering these characters. Hence, my code is saying "If the key is one of those, then let it pass."
Ok, so below is the code for the text1 TextBox to prevent users from entering unwanted stuff. It works great, however I have 3 text boxes on my form & would like to check them all WITHOUT retyping the same rutine 3 times.
Can you guys let me know how to write all-purpose Sub/Function that will do the same thing for any text box (not just 'Text1'). Go Reusability!!!
As always Thanks for your help.
---------------------------------------------------------
Private Sub Text1_KeyPress(KeyAscii As Integer)
Dim strChar As String
' Accept the key if its a "control character" ...
If KeyAscii < 32 Then
Exit Sub
End If
strChar = Chr$(KeyAscii)
' Accept the key if it's numeric ...
If strChar >= "0" And strChar <= "9" Then
Exit Sub
End If
strChar = UCase$(strChar)
' Accept the key if it's alpha ...
If strChar >= "A" And strChar <= "Z" Then
Exit Sub
End If
' Otherwise, reject the key ...
KeyAscii = 0
End Sub
---------------------------------------------------------