Sometimes it's useful to be able to restrict the entry of certain characters into your Userform text boxes. For instance to allow numeric characters only, restrict to uppercase etcà Here's how you do it.
a) Allow uppercase letters only.
Private Sub textbox1_KeyPress(ByVal KeyAscii As MSForms.ReturnInteger)
'
' allow uppercase letters only
'
If KeyAscii >= 97 And KeyAscii <= 122 Then
KeyAscii = KeyAscii - 32
End If
End Sub
b) Disallow all normal input (still allows special keys such as delete, CTRL-C, CTRL-V)
Private Sub textbox1_KeyPress(ByVal KeyAscii As MSForms.ReturnInteger)
KeyAscii = 0
End Sub
c) Disallow all key input
Private Sub textbox1_KeyDown(ByVal KeyCode As MSForms.ReturnInteger, ByVal Shift As Integer)
KeyCode = 0
End Sub
d) Allow numeric characters only
Private Sub textbox1_KeyPress(ByVal KeyAscii As MSForms.ReturnInteger)
'
'
If KeyAscii < 48 or KeyAscii > 57 Then
KeyAscii = 0
End If
Note that copying and pasting text into a textbox circumvents the above checks so you should also add additional checking code on for example the change event for the textbox.
This site uses cookies to help personalise content, tailor your experience and to keep you logged in if you register.
By continuing to use this site, you are consenting to our use of cookies.