access限製文本框輸入的長度

2019-09-28 16:27:00
tmtony8
原創
233

在應用程序中,如姓名,號碼等爲瞭避免錯誤,我們有時會限製文本框録入的內容的長度。

在非綁定的文本框中,我們可以通過掩碼來限製,但是這種方法很多弊端,這裡先不作討論

這裡介紹一下用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)


當輸入大於預設值時,會限製録入或者提示錯誤。

    分享