views:

225

answers:

2

Hellow

I am looking for an elegant solution to determine if a variant is a whole number in VBA. Unfortunately, if the variant was created from a string, I am stuck. Here's a little test script:

dim v as variant
v = "42"
if v <> round(v) then
   msgBox("<>")
end if

Here, the msgBox pops up, probably because the variant was created from a string, although I would have expected v to be = round(v).

A: 

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
Philippe Grondier
That will not quite work in some cases, for example:Dim v As Currencyv = -123456.0000006
Remou
Well, my proposition was more 'write something like that' than 'this is guaranteed bullet proof code', but the main idea is here, even if it needs some extra testing.
Philippe Grondier
I'm sorry, but I have to say -1, even given your caveat about "something like that". Either of your answers as they are coded have bugs. If you present code, it should be correct and not leave finding the bugs as an excercise.
jtolle
Well I don't really agree with your last point "not leave finding bugs as an exercise". Basically finding bugs is a daily exercise for each one of us, as writing code with bugs is our daily reality! Anyway next time I will add all legal mentions to indicate that my answer is presented 'as is', and do not include any garantee of any kind for the user, who seemed to find my answer helpful enough to accept it.
Philippe Grondier
-1 for defending instead of improving. The example is fine if you just use Clng instead of CInt
Oorang
... and I should also add that I do not abandon any of my rights, among them the right to defend my position, when publishing answers and comments on stackoverflow! Sorry guys but I really find your 'offended' position quite excessive. And if you have a better answer or proposal than mine, why don't you post it?
Philippe Grondier
A: 
Sub test()

    Dim v As Variant
    v = "42"
    If Val(v) <> Int(Val(v)) Then
       MsgBox ("<>")
    End If

End Sub

If you use Val(), it will try its best to convert to a number. If it can't, it will return zero and Val(v) will always equal Int(Val(v)) in that case.

Dick Kusleika