Sub LimitKeyPress(ctl As Control, iMaxLen As Integer, KeyAscii As Integer)
On Error GoTo Err_LimitKeyPress
' Purpose: Limit the text in an unbound text box/combo.
' Usage: In the control's KeyPress event procedure:
' Call LimitKeyPress(Me.MyTextBox, 12, KeyAscii)
' Note: Requires LimitChange() in control's Change event also.
If Len(ctl.Text) - ctl.SelLength >= iMaxLen Then
If KeyAscii <> vbKeyBack Then
KeyAscii = 0
Beep
End If
End If
Exit_LimitKeyPress:
Exit Sub
Err_LimitKeyPress:
Call LogError(Err.Number, Err.Description, "LimitKeyPress()")
Resume Exit_LimitKeyPress
End Sub
Sub LimitChange(ctl As Control, iMaxLen As Integer)
On Error GoTo Err_LimitChange
' Purpose: Limit the text in an unbound text box/combo.
' Usage: In the control's Change event procedure:
' Call LimitChange(Me.MyTextBox, 12)
' Note: Requires LimitKeyPress() in control's KeyPress event also.
If Len(ctl.Text) > iMaxLen Then
MsgBox "Truncated to " & iMaxLen & " characters.", vbExclamation, "Too long"
ctl.Text = Left(ctl.Text, iMaxLen)
ctl.SelStart = iMaxLen
End If
Exit_LimitChange:
Exit Sub
Err_LimitChange:
Call LogError(Err.Number, Err.Description, "LimitChange()")
Resume Exit_LimitChange
End Sub