字符串仅包含某些字符

时间:2020-07-02 06:05:22

标签: vba

我是VBA的新手,VBA中的语法对我不是很友好。我正在尝试验证字符串类型的字段。在该特定字段中,我希望字符串仅包含字母,逗号和空格。

这是我目前的方法:

myArray = Array("a", "b", "c", "d", "e", "f", "g", "h", "i", "j", "k", "l", "m", "n", "o", "p", "q", "r", "s", "t", "u", "v", "w", "x", "y", "z", " ", ",", "-", "A", "B", "C", "D", "E", "F", "G", "H", "I", "J", "K", "L", "M", "N", "O", "P", "Q", "R", "S", "T", "U", "V", "W", "X", "Y", "Z")

If Not IsInArray(erName.Text, myArray) Then
   valid = False
   erName.ForeColor = vbRed
End If

IsInArray函数如下所示:

Public Function IsInArray(stringToBeFound As String, arr As Variant) As Boolean
   Dim i
   For i = LBound(arr) To UBound(arr)
      If arr(i) = stringToBeFound Then
          IsInArray = True
          Exit Function
      End If
   Next i
   IsInArray = False
End Function

但这不是一种非常有效的方法,因为我不想遍历字符串中每个字符的数组。有没有执行此验证的简单方法?任何帮助表示赞赏。谢谢。

2 个答案:

答案 0 :(得分:0)

您不必遍历每个字符来检查它是否位于您定义的数组中。您只需要检查给定字符是否在允许的ASCII值范围内:

字符i的ASCII值> = 65和<= 90(对于大写字母)

OR

字符i的ASCII值> = 97和<= 122(用于小写字母)

OR

字符i == 44(对于逗号)的ASCII值

OR

字符i == 32(用于空格)的ASCII值

您可以定义这四个条件的检查以避免循环。

Public Function IsInArray(stringToBeFound As String) As Boolean


Dim i
   For i = 1 to Len(stringToBeFound)
  If (stringToBeFound(i) >= 65 and  stringToBeFound(i) <= 90) or (stringToBeFound(i) >= 97 and  stringToBeFound(i) <= 122) or
(stringToBeFound(i) = 44) or 
(stringToBeFound(i) = 32) Then
      IsInArray = True
      Exit Function
  End If


Next i


IsInArray = False
End Function

答案 1 :(得分:0)

RegEx解决方案

Function StringCheck(str)
    Set objRegEx = New RegExp
    With objRegEx
        .IgnoreCase = True
        .Global = False
        .MultiLine = False
        .Pattern = "[a-zA-Z, ]*" 'alphabets + comma + space
    End With
    
    Set objMatch = objRegEx.Execute(str)
    If objMatch.Count = 1 Then
        If Len(str)=Len(objMatch(0).Value) Then 'if len of string matches the regex find
            StringCheck = True
        Else
            StringCheck = False
        End If
    Else
        StringCheck = False
    End If
End Function

MsgBox StringCheck("Pankaj Jaju") 'True
MsgBox StringCheck("Pankaj_Jaju") 'False
MsgBox StringCheck("Pankaj,Jaju") 'True
MsgBox StringCheck("Pankaj,Jaju 1234") 'False