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.”
I don't believe that documentation. Consider the following simple example (run in Excel 2010):
Sub checkIntegerVsLong()
'Check the total memory allocation for an array
Dim bits As Integer 'or long? :)
Dim arrInteger() As Integer
ReDim arrInteger(1 To 5)
arrInteger(1) = 12
arrInteger(2) = 456
'get total memory allocation for integer in array
bits = VarPtr(arrInteger(2)) - VarPtr(arrInteger(1))
Debug.Print "For integer: " & bits & " bits and " & bits * 8 & " bytes."
Dim arrLong() As Long
ReDim arrLong(1 To 5)
arrLong(1) = 12
arrLong(2) = 456
'get memory allocation for long
bits = VarPtr(arrLong(2)) - VarPtr(arrLong(1))
Debug.Print "For long: " & bits & " bits and " & bits * 8 & " bytes."
End Sub
This prints:
For integer: 2 bits and 16 bytes.
For long: 4 bits and 32 bytes.
You can also test this on individual variables using the following:
Sub testIndividualValues()
Dim j As Long
Dim i As Integer
Dim bits As Integer
bits = LenB(i)
Debug.Print "Length of integer: " & bits & " bits and " & bits * 8 & " bytes."
bits = LenB(j)
Debug.Print "Length of long: " & bits & " bits and " & bits * 8 & " bytes."
End Sub
which prints
Length of integer: 2 bits and 16 bytes.
Length of long: 4 bits and 32 bytes.
Last, you can use a type comparison here:
Public Type myIntegerType
a As Integer
b As Integer
End Type
Public Type myLongType
a As Long
b As Long
End Type
Public Sub testWithTypes()
Dim testInt As myIntegerType
Dim testLong As myLongType
Dim bits As Integer
bits = VarPtr(testInt.b) - VarPtr(testInt.a)
Debug.Print "For integer in types: " & bits & " bits and " & bits * 8 & " bytes."
bits = VarPtr(testLong.b) - VarPtr(testLong.a)
Debug.Print "For long in types: " & bits & " bits and " & bits * 8 & " bytes."
End Sub
which also prints:
For integer in types: 2 bits and 16 bytes.
For long in types: 4 bits and 32 bytes.
This is pretty compelling evidence to me that VBA actually does treat Integer
and Long
differently.
If VBA silently converted behind the scenes, you would expect those to return the same number of bits/bytes for each of the pointer allocations locations. But in the first case, with Integer, it is only allocating 16 bits, while for Long variables, it allocates 32 bits.
So to your question of
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!
It makes complete sense that you would get an Overflow error, as VBA has not actually allocated the memory for a Long
to the Integer
declaration.
I would be curious too if this returns the same on all versions of Office. I can only test on Office 2010 on 64 bit Windows 7.