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

TitanTheYaphet picture TitanTheYaphet · Apr 20, 2014 · Viewed 14k times · Source

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.

Answer

user2426679 picture user2426679 · Oct 7, 2018

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