2010-11-19 51 views

回答

2

如果你想最简单的方法,你可以用这个去:

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 

有在功能上没有错误的“保护”,因此,如果你尝试检查一个过大的数字,如22222222222222,它不会工作。

+2

四位数负数将通过这两个测试 - 例如-3621有五个字符并且是数字。小数点(36.21)或千分隔符(3,621)也会导致问题 – barrowc 2010-11-20 03:06:03

+0

够正确!另外,如果字符串是“00005”,它会通过我认为的验证。 – Tipx 2010-11-25 18:26:12

4
yourString Like "#####" 
1

类似问题以前问:link text

基本上要检查

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

您还可以使用正则表达式来解决此问题。如果在VBA项目中包含Microsoft VBScript Regular Expressions 5.5,则可以使用RegExpMatchCollection变量,如下面的函数中所示。 (这是在ozgrid.com应对this post的变形例。)

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 
相关问题