elmama
​A selection of topics on IT and its application to finance. 
​Send me your comments, questions ​or suggestions by clicking
h​ere


Restricting data entry in VB/VBA textboxes


Sometimes it's useful to be able to restrict the entry of certain characters into your 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

End Sub