Article ID: 152050
Article Last Modified on 1/19/2007
Input Mask: CCCCC
Sub LimitFieldSize (KeyAscii, MAXLENGTH)
Dim C As Control
Dim CLen As Integer
Set C = Screen.ActiveControl
' Exit if a non-printable character is typed.
If KeyAscii < 32 Then Exit Sub
' Exit if typing replaces a selection.
If C.SelLength > 0 Then Exit Sub
' Fetch length of current contents + 1 for the character typed.
CLen = Len(C.Text & "") + 1
' Are there trailing spaces to contend with?
If C.SelStart + 1 > CLen Then CLen = C.SelStart + 1
' Is length of string greater than max?
If CLen > MAXLENGTH Then
Beep
KeyAscii = 0
End If
End Sub
Call the LimitFieldSize procedure from the KeyPress event of each unbound
text box control that you want to limit. You must pass the KeyAscii
parameter supplied by the KeyPress event and the number of characters you
want to limit typing to:
Sub MyUnboundTextBox_KeyPress (KeyAscii As Integer)
LimitFieldSize KeyAscii, 50
End Sub
Keywords: kbhowto kbprogramming kbusage KB152050