Vba 确保字符串正好是5位数字

Vba 确保字符串正好是5位数字,vba,Vba,如果某些字符串='XXXXX',我想返回true 其中,每个X是一个0到9的数字 我知道一定有十几种方法可以做到这一点,但我想知道最好的方法。之前提出的类似问题: yourString Like "#####" 基本上是想检查一下 (Len(s) = 5) And IsNumeric(s) 如果你想要最简单的方法,你可以这样做: Function MyFunction(myString As String) As Boolean MyFunction = ((Len(myString

如果某些字符串='XXXXX',我想返回true

其中,每个X是一个0到9的数字


我知道一定有十几种方法可以做到这一点,但我想知道最好的方法。

之前提出的类似问题:

yourString Like "#####"
基本上是想检查一下

(Len(s) = 5) And IsNumeric(s)

如果你想要最简单的方法,你可以这样做:

Function MyFunction(myString As String) As Boolean
    MyFunction = ((Len(myString) = 5) And (IsNumeric(myString)))
End Function
如果您想要更有效的方法,您必须对人们建议的不同方法运行一些测试

编辑:前面的解决方案不太好(见前2条评论),但我还是让它存在,因为它已经被接受了。下面是我要做的:

Function MyFunction(myString As String) As Boolean
    Dim myDouble As Double
    Dim myLong As Long
    myDouble = Val(myString)
    myLong = Int(myDouble / 10000)
    MyFunction = ((Len(myString) = 5) And (myLong > 0) And (myLong < 10))
End Function
Function MyFunction(myString作为字符串)作为布尔值
把我的双倍当作双倍
暗淡如长
myDouble=Val(myString)
myLong=Int(myDouble/10000)
MyFunction=((Len(myString)=5)和(myLong>0)以及(myLong<10))
端函数

该函数中没有错误“protection”,因此,如果您试图检查像22222这样的过大数字,它将不起作用。

您也可以使用正则表达式来解决此问题。如果在VBA项目中包括Microsoft VBScript正则表达式5.5,则可以在下面的函数中使用
RegExp
MatchCollection
变量。(这是对ozgrid.com上回复的修改。)


四位负数将通过这两项测试-例如,-3621有五个字符,是数字。小数点(36.21)或千位分隔符(3621)也会引起足够的问题!另外,如果字符串是“00005”,我认为它将通过验证。
Public Function FiveDigitString(strData As String) As Boolean

On Error GoTo HandleError

Dim RE As New RegExp
Dim REMatches As MatchCollection

    With RE
        .MultiLine = False
        .Global = False
        .IgnoreCase = True
        .Pattern = "^[0-9][0-9][0-9][0-9][0-9]$"
    End With

    Set REMatches = RE.Execute(strData)
    If REMatches.Count = 1 Then
        FiveDigitString = True
    Else
        FiveDigitString = False
    End If

    Exit Function
HandleError:
    Debug.Print "Error in FiveDigitString: " & Err.Description
    FiveDigitString = False
End Function