I Googled and found the code below to limit the number of characters that can be entered in an unbound textbox. I call this in the "On Change" event and "On KeyPress" event. In certain instances I get the 2185 error "You can't reference a property or method for a control unless the control has focus." I'm not sure what I'm doing wrong. I do not have a .SetFocus anywhere. Any help?
================================================== ======
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()")
MsgBox "Error " & Err.Number & ": " & Err.Description
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()")
MsgBox "Error " & Err.Number & ": " & Err.Description
Resume Exit_LimitChange
End Sub
================================================== ======