J
Joe in Australia via OfficeKB.com
I came across a bug recently and I was wondering if anyone else has
encountered it. When I calculate the expression in the routine below I get
one result if I print it and another result if I save it to a variable - even
if I just save the string representation of it! The subroutine runs the test
on three consecutive numbers, so you see it work correctly in two tests and
fail in a third.
Sub BuggyIntegers()
' This routine demonstrates inconsistent behavior in
' VBA's integer conversion
Dim MyVar As Integer
Dim Unity As Variant
Dim MyString As String: MyString = ""
' These numbers aren't magic - they just demonstrate the problem
' quickly. Change them to any integers >= 2 to explore other results
For MyVar = 16 To 18
' This variable should always equal 1.
Unity = Int(Log(MyVar) / Log(MyVar))
' But if it doesn't equal 1, it should at least equal itself!
MsgBox _
"Compare the values when MyVar equals " _
& MyVar _
& " : " _
& Unity _
& " " _
& Int(Log(MyVar) / Log(MyVar))
' Let's save the results so we can compare them later.
MyString = MyString & vbCr & Unity & " " & Int(Log(MyVar) / Log(MyVar)
)
Next MyVar
' Print the results in one go.
MyString = _
"And now look at the same results assigned to a variable!" _
& vbCr _
& MyString
MsgBox MyString
End Sub
encountered it. When I calculate the expression in the routine below I get
one result if I print it and another result if I save it to a variable - even
if I just save the string representation of it! The subroutine runs the test
on three consecutive numbers, so you see it work correctly in two tests and
fail in a third.
Sub BuggyIntegers()
' This routine demonstrates inconsistent behavior in
' VBA's integer conversion
Dim MyVar As Integer
Dim Unity As Variant
Dim MyString As String: MyString = ""
' These numbers aren't magic - they just demonstrate the problem
' quickly. Change them to any integers >= 2 to explore other results
For MyVar = 16 To 18
' This variable should always equal 1.
Unity = Int(Log(MyVar) / Log(MyVar))
' But if it doesn't equal 1, it should at least equal itself!
MsgBox _
"Compare the values when MyVar equals " _
& MyVar _
& " : " _
& Unity _
& " " _
& Int(Log(MyVar) / Log(MyVar))
' Let's save the results so we can compare them later.
MyString = MyString & vbCr & Unity & " " & Int(Log(MyVar) / Log(MyVar)
)
Next MyVar
' Print the results in one go.
MyString = _
"And now look at the same results assigned to a variable!" _
& vbCr _
& MyString
MsgBox MyString
End Sub