2010-11-19 47 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 
相關問題