Check if field contains any numbers?

2019-07-20 02:49发布

Hi I'm trying to write some VBA so that it checks whether one of my text boxes contains a number. The text box is called: CustomerName. Here's the code I am currently using:

Function HasNumber(strData As String) As Boolean
    Dim iCnt As Integer

    For iCnt = 1 To Len(strData)
        If IsNumeric(Mid(strData, iCnt, 1)) Then
            HasNumber = True
            Exit Function
        End If
    Next iCnt

End Function

Private Sub CustomerName_AfterUpdate()
If HasNumber(CustomerName) Then
    MsgBox "Only letters are allowed for this field."
    Exit Sub
End If

End Sub

For some reason when I enter numbers into this field and then click out of it (i.e. update it) it doesn't come up with a msgbox or anything. What can I do to fix this?

2条回答
狗以群分
2楼-- · 2019-07-20 03:15

Instead of using some custom code, I would use this validation rule on the CustomerName column of your table, or on the validation rule of your text box:

Not Like "*[0-9]*"

See here for a reference of validation rules.

查看更多
家丑人穷心不美
3楼-- · 2019-07-20 03:22

Try it like this:

If HasNumber(CustomerName.Text) Then
查看更多
登录 后发表回答