office交流網(wǎng)--QQ交流群號及微信交流群

Access培訓(xùn)群:792054000         Excel免費(fèi)交流群群:686050929          Outlook交流群:221378704    

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

微信交流群(請用微信掃碼)

        

access限製文本框輸入的長度

2019-09-28 16:27:00
tmtony8
原創(chuàng)
4585

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

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

這裡介紹一下用vba代碼如何限製録入的長度

如圖,在窗體中添加一箇“text2”非綁定文本框



將下麵兩箇函數(shù)粘貼到模塊中。

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事件中調(diào)用LimitKeyPress()。如將名爲(wèi)“text2”的文本框限製爲(wèi)8箇字符,其KeyPress事件爲(wèi):
 Call LimitKeyPress(Me.Text2, 8, KeyAscii)
在文本框的Change事件中調(diào)用LimitChange()。衕上,更改事件過程爲(wèi):
Call LimitChange(Me.Text2, 8)


當(dāng)輸入大於預(yù)設(shè)值時,會限製録入或者提示錯誤。

    分享
    文章分類
    聯(lián)繫我們
    聯(lián)繫人: 王先生
    Email: 18449932@qq.com
    QQ: 18449932
    微博: officecn01
    移動訪問