在应用程序中,如姓名,号码等为了避免错误,我们有时会限制文本框录入的内容的长度。
在非绑定的文本框中,我们可以通过掩码来限制,但是这种方法很多弊端,这里先不作讨论
这里介绍一下用vba代码如何限制录入的长度
如图,在窗体中添加一个“text2”非绑定文本框
将下面两个函数粘贴到模块中。
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 IfExit_LimitKeyPress: Exit SubErr_LimitKeyPress: MsgBox "Error " & Err.Number & ": " & Err.Description Resume Exit_LimitKeyPressEnd SubSub 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 "不能超过" & iMaxLen & " 字符