How can I check if a string only contains letters?

后端 未结 4 1731
耶瑟儿~
耶瑟儿~ 2020-12-06 17:52

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

相关标签:
4条回答
  • 2020-12-06 18:13

    Try this for IsAlpha

    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
                    IsAlpha = True
                Case Else
                    IsAlpha = False
                    Exit For
            End Select
        Next
    End Function
    
    0 讨论(0)
  • 2020-12-06 18:29

    The most direct, concise, and performant way to check if a string contains only alpha characters is with this function:

    Function IsAlpha(s) As Boolean
        IsAlpha = Len(s) And Not s Like "*[!a-zA-Z]*"
    End Function
    
    0 讨论(0)
  • 2020-12-06 18:33

    Left(Me.TxtDxCode.Text, 2) returns the first two characters of the string. So, if Me.TxtDxCode.Text was 7ZABC, this expression would return "7Z". This would cause the IsAlpha test to fail.

    As you want to examine just the 2nd character, use Mid$ instead:

    If IsAlpha(Mid$(Me.TxtDxCode.Text, 2, 1)) Then

    This will return "Z" and the IsAlpha test should now succeed

    (The string versions Left$, Mid$ etc are slightly faster than the variant versions Left, Mid etc - see here)

    0 讨论(0)
  • 2020-12-06 18:37

    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.

    0 讨论(0)
提交回复
热议问题