Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
752 views
in Technique[技术] by (71.8m points)

vba - How can I check if a string only contains letters?

I'm using a function that allows me to review a string of text and evaluate if it is composed of letters. It is housed in a module called "General". The general module only exists to house public functions and variables. Function code is listed below:

Public Function IsAlpha(strValue As String) As Boolean
Dim intPos As Integer

    For intPos = 1 To Len(strValue)
        Select Case Asc(Mid(strValue, intPos, 1))
            Case 65 To 90, 97 To 122
                IsLetter = True
            Case Else
                IsLetter = False
                Exit For
        End Select
    Next
End Function  

Next I have two "if" routines that evaluate the first 2 characters of a textbox in my userform. The first routine asks if the 1st character is numeric and the second routine asks if the 2nd character is alpha. Currently, the second "if" routine is ejecting me from the sub-routine when IsAlpha tests True, rather than generating the MsgBox. Is the IsAlpha function not being called correctly?

If routines code listed below:

Private Sub CmdMap_Click()

    With TxtDxCode
        If IsNumeric(Left(Me.TxtDxCode.Text, 1)) Then
            MsgBox "Incorrect DX Code format was entered. ", vbExclamation, "DX Code Entry"
            TxtDxCode.Value = ""
            TxtDxCode.SetFocus
            Exit Sub
        End If

        If IsAlpha(Left(Me.TxtDxCode.Text, 2)) Then
            MsgBox "Incorrect DX Code format was entered. ", vbExclamation, "DX Code Entry"
            TxtDxCode.Value = ""
            TxtDxCode.SetFocus
            Exit Sub
        End If
    End With
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Why don't you use regular expressions instead? Then there's no loops involved:

Public Function IsAlpha(strValue As String) As Boolean
    IsAlpha = strValue Like WorksheetFunction.Rept("[a-zA-Z]", Len(strValue))
End Function

Also, when you create a User-Defined Function (UDF) you need to ensure that the return value is assigned to the name of the actual function, in this case IsAlpha - not IsLetter otherwise the value will never be passed back.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...