Integer

The Integer data type can contain whole numbers between -32,768 and 32,767.
This data type uses 2 bytes.
One byte is used to represent the sign (either positive or negative).
The default value is 0.

Dim myInteger As Integer 

Adding Two Numbers

Declare two variables with the values (5 and 12) and add them together.

Dim myInteger1 As Integer 
Dim myInteger2 As Integer
Dim myResult As Integer

myInteger1 = 5
myInteger2 = 12
myResult = myInteger1 + myInteger2

Debug.Print myResult ' = 17

Integer Rounding <> 0.5

Declare two variables with the values (5.4) and 12.6) and add them together.

Dim myInteger1 As Integer 
Dim myInteger2 As Integer
Dim myResult As Integer

myInteger1 = 5.4 ' rounded down to 5
myInteger2 = 12.6 ' rounded up to 13
myResult = myInteger1 + myInteger2

Debug.Print myResult ' = 18

Integer Rounding - 0.5

Declare two variables with the values (5.5) and 12.5) and add them together.
Any fractional parts equal to 0.5 are rounded (down or up) to the nearest even number.
Although this type of rounding is unusual it is by design to compensate for a bias that could accumulate when adding a lot of 0.5 fractions.

Dim myInteger1 As Integer 
Dim myInteger2 As Integer
Dim myResult As Integer

myInteger1 = 0.5 ' rounded down to 0
myInteger2 = 0.5 ' rounded down to 0
myResult = myInteger1 + myInteger2
Debug.Print myResult ' = 0

myInteger1 = 1.5 ' rounded up to 2
myInteger2 = 1.5 ' rounded up to 2
myResult = myInteger1 + myInteger2
Debug.Print myResult ' = 4

myInteger1 = 1.5 ' rounded up to 2
myInteger2 = 2.5 ' rounded down to 2
myResult = myInteger1 + myInteger2
Debug.Print myResult ' = 4

Integer is converted to Long

On 32-bit systems the Integer data type is implicitly converted to a Long data type.
However this conversion does not mean that a larger range can be accepted.
If you declare an Integer data type it can still only contain a number between -32,768 and 32,767.
For this reason there is no point declaring any variables with an Integer data type.
There used to be a performance advantage to using Integer over a Long but that is no longer the case.
In fact using a Long data type might actually be faster than using an Integer data type because there is no implicit conversion.
It is worth noting though that some old API functions may still expect an Integer data type.
If you pass a Long (4 bytes) when it is expecting an Integer (2 bytes) it will not work due to the different byte sizes.


Large Numbers

The following code will generate an error.

Dim myInteger As Integer 
myInteger = 40000
Call MsgBox(TypeName(myNumber))
alt text

Conversion Function

The CINT function returns an expression converted to an Integer data type.


© 2024 Better Solutions Limited. All Rights Reserved. © 2024 Better Solutions Limited TopPrevNext