How to determine if a variant is an integer in VBA?

I am looking for an elegant solution to determine if a variant is an integer 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

MsgBox appears here, probably because the option was created from a string, although I expected v to be = round (v).

+5
source share
2 answers

You should write something like:

if cDbl(v) <> round(cDbl(v)) Then

Where cDbl is a function that converts any data to a double type number. You may need to consider cases where v cannot be converted to a number using the isNumeric () function before calling the cDbl function. You can use the cInt function to compare:

if isnumeric(v) then
    if cDbl(v) - cInt(v) <> 0 Then
    ....
    endif
else
   debug.print "data cannot be converted to a number"
endif
+9
Sub test()

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

End Sub

Val(), . , , Val (v) Int (Val (v)) .

+3

All Articles