How do I validate whether a string is just a number or not?
if val like...
if val <> ...
someone suggested an imaginary function called isnumber
if isnumber(val) = true/false
this didn't work, any suggestions
First -- don't use 'val' as a variable name. It's a built-in function.
Although VBA will allow you to use it, it may confuse the Basic
interpreter and it will certainly confuse you at some point.
Second -- the built-in (not imaginary) function is called IsNumeric,
and it does indeed return true or false depending on whether the
string input represents a number. It will accept thousands separators
and at most one decimal separator -- I think it checks the current
Regional settings to determine what characters are assigned to the
separators.
Third, the Val function converts a string to a number, if possible,
according to certain rules. Those rules are different than those for
IsNumeric. Val will convert any numeric characters at the start of the
string, and stop at the first nonnumeric character; so Val("123abc")
returns the integer 123. If the string is empty or doesn't start with
a numeric part, it returns 0. In both of those cases, IsNumeric
returns false.
Play with this macro for a bit to see the differences:
Sub Demo()
Dim s As String
s = InputBox("Number:")
If IsNumeric(s) Then
MsgBox s & " is a number" & vbCr & _
"Val(s) = " & Val(s)
Else
MsgBox s & " is not a number" & vbCr & _
"Val(s) = " & Val(s)
End If
End Sub
Finally, there are type conversion functions such as CInt(), CLng(),
CSng(), and CDbl(). See the help topic "Type Conversion Functions" for
the full list. If the input expression for these functions isn't
completely numeric, they'll throw an error, so you need to check first
with IsNumeric or use an On Error trap. Also, CInt() throws an error
if the input is numeric but bigger than 32767.
--
Regards,
Jay Freedman
Microsoft Word MVP
Email cannot be acknowledged; please post all follow-ups to the
newsgroup so all may benefit.