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

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

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

微信交流群(請(qǐng)用微信掃碼)

        

access限制文本框輸入的長(zhǎng)度

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

在應(yīng)用程序中,如姓名,號(hào)碼等為了避免錯(cuò)誤,我們有時(shí)會(huì)限制文本框錄入的內(nèi)容的長(zhǎng)度。

在非綁定的文本框中,我們可以通過(guò)掩碼來(lái)限制,但是這種方法很多弊端,這里先不作討論

這里介紹一下用vba代碼如何限制錄入的長(zhǎng)度

如圖,在窗體中添加一個(gè)“text2”非綁定文本框



將下面兩個(gè)函數(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 "不能超過(guò)" & 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()。如將名為“text2”的文本框限制為8個(gè)字符,其KeyPress事件為:
 Call LimitKeyPress(Me.Text2, 8, KeyAscii)
在文本框的Change事件中調(diào)用LimitChange()。同上,更改事件過(guò)程為:
Call LimitChange(Me.Text2, 8)


當(dāng)輸入大于預(yù)設(shè)值時(shí),會(huì)限制錄入或者提示錯(cuò)誤。

    分享
    文章分類(lèi)
    聯(lián)系我們
    聯(lián)系人: 王先生
    Email: 18449932@qq.com
    QQ: 18449932
    微博: officecn01
    移動(dòng)訪(fǎng)問(wèn)