Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations Mike Lewis on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Restrict data entry in userform text boxes

VBA How To

Restrict data entry in userform text boxes

by  taupirho  Posted    (Edited  )

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.
Register to rate this FAQ  : BAD 1 2 3 4 5 6 7 8 9 10 GOOD
Please Note: 1 is Bad, 10 is Good :-)

Part and Inventory Search

Back
Top