0
A
回答
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,它不會工作。
4
yourString Like "#####"
1
1
您還可以使用正則表達式來解決此問題。如果在VBA項目中包含Microsoft VBScript Regular Expressions 5.5,則可以使用RegExp
和MatchCollection
變量,如下面的函數中所示。 (這是在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
相關問題
- 1. 字符串操作(確保字符串總是以完全相同「//」前面)
- 2. 如何編寫確保字符串正好是5位數字的Java代碼
- 3. 確保字符串每n個字符都有一箇中斷字符
- 4. 確保字符串中沒有整數?
- 5. 如何確保在一個字符串中只有一個http://?
- 6. 字符串完全匹配
- 7. 完全替換多個字符串
- 8. Jmock完全匹配字符串參數
- 9. 選擇第一5個字符,在C#字符串數組
- 10. 確定一個字符串是不是另一個字符串
- 11. 分割字符串,每5個字符
- 12. 確保在字符串
- 13. ASP:的RegularExpressionValidator,確保有一個字符串
- 14. 檢查一個字符串是否包含正確位置的子字符串
- 15. java驗證字符串包含數字和搜索,以確保沒有字符
- 16. 保存輸入字符串字符到一個二維數組
- 17. 分裂字符串,但保持內部字符串完好?
- 18. 檢查一個字符串是否全部是數字和10個字符長
- 19. 錯誤使用+ =一個字符追加到字符串:字符串是不完全相同的UINT8
- 20. 每N個字符/數字分割一個字符串/數字?
- 21. SQL - 根據搜索模式輸出一個子字符串,確保首字符/最後一個字符串是全字
- 22. 在Coding4Fun PopUp控件中完全顯示一個長字符串?
- 23. 的Android Linkify一個完全無關的字符串
- 24. C#的輸入與一個字符串完全
- 25. Web客戶端和DownloadString,確保字符串完全下載在TextBlock.Text
- 26. 爲什麼^ \ d + $匹配完全數字的字符串?
- 27. Android WebView未完全解碼字符串
- 28. NSPredicate與字符串完全匹配
- 29. 在PHP中完全字符串輸入
- 30. 如何確定一個字符串包含字符串
四位數負數將通過這兩個測試 - 例如-3621有五個字符並且是數字。小數點(36.21)或千分隔符(3,621)也會導致問題 – barrowc 2010-11-20 03:06:03
夠正確!另外,如果字符串是「00005」,它會通過我認爲的驗證。 – Tipx 2010-11-25 18:26:12