Home >> Computing >> VBA

This page is about trapping, allowing, disallowing, and modifying key presses in VB(A), especially with respect to text boxes.

The easiest way to do this is by example. Suppose you have a textbox called Text1. The example code that I've given below traps the keys to the textbox so that only alphabetic (a-z, A-Z) and numeric (0-9) keys can be entered. Moreover, lower case letters are converted to upper case letters. I have also enabled the Delete key - which is, after all, quite a useful key. Here's the code:

 

Private Sub Text1_KeyPress(KeyAscii As Integer)

Select Case KeyAscii
Case 8: 'allow delete key
Case Asc("a") To Asc("z"): KeyAscii = KeyAscii + Asc("A") - Asc("a") 'convert lower to upper
Case Asc("A") To Asc("Z"), Asc("0") To Asc("9"): 'OK, don't alter the key
Case Else: KeyAscii = 0 'disallow everything else
End Select
End Sub

 


Created: 14-Oct-2004