开发者

formula for validating only string value in excel

开发者 https://www.devze.com 2023-02-03 03:50 出处:网络
I want user to enter only characters in excel cell.. i used ISTEXT(value) 开发者_C百科in custom formula of excel but can\'t get correct output for string likehgdashj2132154 please help...

I want user to enter only characters in excel cell.. i used ISTEXT(value) 开发者_C百科in custom formula of excel but can't get correct output for string like hgdashj2132154 please help... thank u..


It just takes a little regular expression magic. You need a user-defined function and the regular expression add-in. In the Developer view go to Tools|References and tick Microsoft VBScript Regular Expressions 5.5.

Here's the function:

Public Function isOnlyAlpha(myText) As Boolean
   Dim regEx
   Set regEx = New RegExp   'Regular expression object
   regEx.Pattern = "^[a-zA-Z]*$"  ' Set pattern.
   isOnlyAlpha = regEx.Test(myText)   ' Test for match
End Function

The results:

=isOnlyAlpha("hgdashj2132154")
False

=isOnlyAlpha("hgdashj")
True

If you'd rather do without regular expressions, there's always the "Like Loop":

Public Function IsOnlyAlpha(Value As String) As Boolean
    IsOnlyAlpha = True
    Dim i As Integer
    For i = 1 To Len(Value)
        IsOnlyAlpha = IsOnlyAlpha And (Mid(Value, i, 1) Like "[A-Za-z]")
    Next i
End Function


Smack, I found this on my bookmarked sites. It's essentially the same concept as Marc Thibault's suggestion, but doesn't require any additional references:

http://www.techonthenet.com/excel/formulas/alphanumeric.php


A pure VBA approach:

(I edited my answer to use the Like operator instead of the IsNumeric function. Now ONLY characters a to z are considered valid, instead of just non-numeric characters.)

Public Function IsOnlyAlpha(Value As String) As Boolean

If Len(Value) = 0 Then

    IsOnlyAlpha = False
    Exit Function

End If

Dim i As Integer
For i = 1 To Len(Value)

    If Not Mid(Value, i, 1) Like "[A-Za-z]" Then

        IsOnlyAlpha = False
        Exit Function

    End If

Next i

IsOnlyAlpha = True

End Function
0

精彩评论

暂无评论...
验证码 换一张
取 消