IsNumeric Alternative (VB Function)
Posted March 6th, 2009 by Ryan Olbe Visual Basic Projects Add commentsHere's an original idea I came up with as a replacement to the built-in VB IsNumeric function. It gives you complete control over what you consider a number to be. For example, let's say you pass the value $3,207.37 to isNumeric. Now normally this would return true, but what if you didn't want it to return true. What if you wanted it to count the comma and period as a number, but not the dollar sign (i.e. 3,207.37 is a number and $3,207.37 is not). Well normally you wouldn't be able to do anything about it, but with this function you are able to decide which individual characters you think are numeric and which characters you think are not numeric. This function allows you to pass as many characters as you want after the number specifying what you consider a number to be. For example, if you consider the comma (,) and the dollar sign ($) to be "a number", then you would say isNumeric2("333.33", ",$"). After you pass it the initial number (either in string or non-string form), you pass it all of the characters you consider to be numeric in one string, so if you consider the comma, dollar sign and percent sign to be numeric you would say: isNumeric2("$500.23%", ",$%"). And this function will return true (if the number is numeric) and false (if the number is not numeric). Feedback and comments are welcome.
Download is_numeric_alternative.zip (June 11, 2005)

Filelist
Form1.frm
Module1.bas
Public Function isNumeric2(v As Variant, Optional strChars As String) As Boolean
If CStr(v) = "" Then 'if nothing was passed
isNumeric2 = False
Exit Function
End If
Dim i As Integer
For i = 1 To Len(CStr(v))
Select Case Asc(Mid(CStr(v), i, 1))
Case 48 To 57 '0 to 9 was found
'these are good, don't do anything
Case Else
If InStr(strChars, Mid(CStr(v), i, 1)) = 0 Then
isNumeric2 = False
Exit Function
End If
End Select
Next
isNumeric2 = True
End Function
And here's another function I wrote which does the same thing but in a different way...
Public Function isNumeric3(v As Variant, Optional strChars As String) As Boolean
If CStr(v) = "" Then 'if nothing was passed
isNumeric3 = False
Exit Function
End If
Dim keyAsciiCodes(255) As Boolean 'an array of 255 booleans (1 for each KeyAscii char)
If Not IsMissing(strChars) Then 'if strChars exists
Dim j As Integer
For j = 1 To Len(strChars)
keyAsciiCodes(Asc(Mid(strChars, j, 1))) = True 'true means count is as a number
Next
End If
Dim i As Integer
For i = 1 To Len(CStr(v))
Select Case Asc(Mid(CStr(v), i, 1))
Case 48 To 57 '0 to 9 was found
'these are good, don't do anything
Case Else
If keyAsciiCodes(Asc(Mid(CStr(v), i, 1))) = False Then 'character is NOT a number
isNumeric3 = False
Exit Function
End If
End Select
Next i
isNumeric3 = True
End Function