# 如何检查字符串是否仅在vba中包含数字how to check if a string contains only numeric numbers in vba

\$ 8995 2008年4月18日，本田思域Hybrid \$ 8995（Orem）图片地图车和卡车-由所有者

## 4 个回复4

### ===============>>#1 票数：1

``````Option Explicit
Function FindYear(S As String) As Long
Dim SS As Variant
Dim sDate As String
Dim I As Long, J As Long

SS = Split(S, " ")
For I = 0 To UBound(SS) - 2
sDate = ""
For J = 0 To 2
sDate = " " & sDate & " " & SS(I + J)
Next J
sDate = Trim(sDate)
If IsDate(sDate) Then
FindYear = Year(sDate)
Exit Function
End If
Next I
End Function
``````

### ===============>>#2 票数：1

``````Function StringIsDigits(ByVal s As String) As Boolean
StringIsDigits = Len(s) And (s Like String(Len(s), "#"))
End Function
``````

### ===============>>#3 票数：0

``````Const str\$ = "\$8995 Apr 18 2008 Honda Civic Hybrid \$8995 (Orem) pic map cars & trucks - by owner"
Option Explicit
Sub FindNumericValues()

Dim var() As String
Dim numbers As Variant

var = Split(str, " ")

numbers = GetNumerics(var)

MsgBox Join(numbers, ",")

End Sub

Function GetNumerics(words() As String) As Variant
Dim tmp() As Variant
Dim i As Integer
Dim n As Integer
Dim word As Variant
Dim bNumeric As Boolean

For Each word In words
n = 0
bNumeric = True
Do While n < Len(word)
n = n + 1
If Not IsNumeric(Mid(word, n, 1)) Then
bNumeric = False
Exit Do
End If
Loop
If bNumeric Then
ReDim Preserve tmp(i)
tmp(i) = word
i = i + 1
End If
Next

GetNumerics = tmp
End Function
``````

### ===============>>#4 票数：0

``````Public Function GetYear(someText As String) As Integer
With CreateObject("VBScript.RegExp")
.Global = False
.MultiLine = False
.IgnoreCase = True
.Pattern = " [\d]{4} "
If .Test(testString) Then
GetYear = CInt(.Execute(testString)(0))
Else
GetYear = 9999
End If
End With
End Function
``````

``````Public Const testString As String = "\$8995 Apr 18 2008 Honda Civic Hybrid \$8995 (Orem) pic map cars & trucks - by owner "

Public Function GetYear(someText As String) As Integer
With CreateObject("VBScript.RegExp")
.Global = False
.MultiLine = False
.IgnoreCase = True
.Pattern = " [\d]{4} "
If .Test(testString) Then
GetYear = CInt(.Execute(testString)(0))
Else
GetYear = 9999
End If
End With
End Function

Sub Foo()
Debug.Print GetYear(testString) '// "2008"
End Sub
``````