how to check if a string contains only numeric numbers in vba

15,450

Solution 1

This can be accomplished as a single line of code, using the Like operator

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

Solution 2

Will it be the case that all the strings with "years" will have substrings that look like dates? If that is the case, you could just cycle through the string looking for the first group of three that looks like a date, extracting the year from that:

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
Share:
15,450
TitanTheYaphet
Author by

TitanTheYaphet

Updated on June 04, 2022

Comments

  • TitanTheYaphet
    TitanTheYaphet almost 2 years

    I want to parse out the year info from a string like this one

    $8995 Apr 18 2008 Honda Civic Hybrid $8995 (Orem) pic map cars & trucks - by owner

    Since I retrieve this string online, sometimes the year element is not at the same place. The way I do it is to split the string by space using split function, then check if each node of the array contains only numeric digits.

    However when i use the function IsNumeric, it also returns "$8995" node as true as well.

    What is a good way to check if a string contains only numbers, no "$", no ".", not anything else?

    Or in my situation, is there a better way to retrieve the year information?

    Thanks.

  • chris neilsen
    chris neilsen about 10 years
    should be For I = 0 To UBound(SS) - 2
  • Ron Rosenfeld
    Ron Rosenfeld about 10 years
    @chrisneilsen Thanks! I will change it.