Microsoft Access - Programmatically Limit The Length Of Text Box Responses With The KeyPress Event (Access 2000/2002/2003)

As you may know, you can always apply an input mask to a control in Access to limit the number of characters the user enters into the field. However, if the maximum length is a large number or the maximum length varies based on other form criteria, a mask just isn't practical. In such cases, you can use the KeyPress event restrict the field length. This event procedure has a single integer argument called KeyAscii that identifies the key that the user just pressed. However, you can also use this argument to ignore any keys pressed after the field length reaches a certain point. Consider the following code:

  • Private Sub Text1_KeyPress(KeyAscii As Integer)
  •           If (Len(Text1.Text) + 1) > 5 And _
  •           KeyAscii <> Asc(vbBack) Then KeyAscii = 0
  • End Sub

This code restricts the Text Box to five characters. First, it checks to see if the key the user just pressed will make the field length greater than five. If it will, the code sets the KeyAscii value to 0, which cancels the key press. The code also checks to make sure the key the user pressed is not the Backspace key, since he should be allowed to clear the field at any time.

Go back