Integer Vs Long Confusion
I have seen many believe in the following
VBA converts all integer values to type Long
In fact, even the MSDN article says
“In recent versions, however, VBA converts all integer values to type Long, even if they're declared as type Integer.”
How is this possible? Consider this simple example.
Sub Sample()
Dim I As Integer
I = 123456789
End Sub
If VBA
converts all Integer
values to type Long
even if they're declared as type Integer, then the above should never give you the Overflow
error!
What am I missing here? Or should I take it that the statement is incorrect and pay serious heed to that the link says in the beginning
An integer declared as an Integer
is still type checked as an Integer
. The msdn documentation is referencing how the variable is stored internally. On a 32 bit system, an Integer will be stored in 32 BITS not Bytes, while on a 16 bit system the value is stored in a 16 BIT space or register, it would have been stored in 16. Hence the maximum size.
There is no type conversion going on as far as VBA is concerned. An int is an int and a long is a long, even though they now take up just as much space.
I've spent a lot of time working in the VBA environment and have every reason to believe that the claim in this article is at best, misleading.
I've never come across a situation where an automatic unexpected conversion is made. Of course, assignment by value to a larger type (such as a Double
or Long
) would be implicit.
One specific case where automatic conversion would be a breaking change would be an assignment to a Variant
type. Without a conversion, the type would be VT_I2, with conversion VT_I4.
Passing an Integer type ByRef
to a function expecting a Long
emits a type mismatch in Office 2013.
I suspect they are referring to the internal storage of the Integer
: it's very likely that they are not aligned on 16 bit words in memory (cf. a short
structure member in C / C++). They are probably talking about that.