I am looking to determine if a variant created from a string is a whole number.
Here's a test script:
dim v as variant
v = "42"
if v <> round(v) then
msgBox("<>")
end if
The msgBox pops up, probably because the variant was created from a string, although I would have expected v to be = round(v).
1, First check if the string value is numeric. 2, Compare the floor and ceiling of the number. If it's the same, you have a whole number.
The Variant data type is the data type for all variables that are not explicitly declared as some other type (using statements such as Dim, Private, Public, or Static).
VBA Variant Doesn't Require Explicit Way The general procedure to declare a VBA variable is to first name the variable and then assign the data type to it. Below is an example of the same. This is the explicit way of declaring the variable.
You should write something like:
if cDbl(v) <> round(cDbl(v)) Then
Where cDbl is a function converting any data to a double-type number. You might have to treat cases where v cannot be converted to a number with the isNumeric() function before calling the cDbl function. You can even use the cInt function for your comparisons:
if isnumeric(v) then
if cDbl(v) - cInt(v) <> 0 Then
....
endif
else
debug.print "data cannot be converted to a number"
endif
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With