office交流网--QQ交流群号

Access培训群:792054000         Excel免费交流群群:686050929          Outlook交流群:221378704    

Word交流群:218156588             PPT交流群:324131555

access限制文本框输入的长度

2019-09-28 16:27:00
tmtony8
原创
4082

在应用程序中,如姓名,号码等为了避免错误,我们有时会限制文本框录入的内容的长度。

在非绑定的文本框中,我们可以通过掩码来限制,但是这种方法很多弊端,这里先不作讨论

这里介绍一下用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 If

Exit_LimitKeyPress:
    Exit Sub

Err_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 "不能超过" & iMaxLen & " 字符", 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

在文本框的KeyPress事件中调用LimitKeyPress()。如将名为“text2”的文本框限制为8个字符,其KeyPress事件为:
 Call LimitKeyPress(Me.Text2, 8, KeyAscii)
在文本框的Change事件中调用LimitChange()。同上,更改事件过程为:
Call LimitChange(Me.Text2, 8)


当输入大于预设值时,会限制录入或者提示错误。

    分享