Joe Boatman
New member
- Local time
- Today, 14:50
- Joined
- May 30, 2020
- Messages
- 25
Two Integers multiplied or added together must not exceed 32,767, even if assigned to a Long variable, or run-time error 8 occurs.
In the following code n1 and n2 are Integer types - they can hold numbers from -32,768 to +32,767. So if 1 is added to an integer variable that is set to 32767 it should produce error code 8 in MS Office VBA: Overflow.
What if the sum of 32676 + 1 is put into a Long variable which can hold numbers up to 2,147,483,647? Although each integer variable has been assigned a number less than the maximum permitted for Integer types, VBA is unable to put the result into a Long variable type. This is daft!
It gets worse! See the line of code that adds 1 to 32767? It fails with error 8 again. Edit that line to add 1 to 32768 - this succeeds because VBA must be realising that 32768 is too big to be an integer!
There's no error if n1 and n2 are initially declared as Long types. So if you are dealing with large values like pixels and twips, declare variables with type Long or Single.
In the following code n1 and n2 are Integer types - they can hold numbers from -32,768 to +32,767. So if 1 is added to an integer variable that is set to 32767 it should produce error code 8 in MS Office VBA: Overflow.
What if the sum of 32676 + 1 is put into a Long variable which can hold numbers up to 2,147,483,647? Although each integer variable has been assigned a number less than the maximum permitted for Integer types, VBA is unable to put the result into a Long variable type. This is daft!
It gets worse! See the line of code that adds 1 to 32767? It fails with error 8 again. Edit that line to add 1 to 32768 - this succeeds because VBA must be realising that 32768 is too big to be an integer!
Code:
Private Sub Integer_TEST()
'Use F8 to step through this code
'Show Locals Window (View menu) to view the values in the variables
Dim n1 As Integer, n2 As Integer 'numbers ranging in value from -32,768 to 32,767
Dim nLong As Long 'numbers ranging in value from -2,147,483,648 to 2,147,483,647
n1 = 32767
n2 = 1
nLong = n1 + n2 'Err 8: Overflow
nLong = 32767 + 1 'Also Err 8
nLong = 32767 * 1 'Is OK
nLong = 32767 * 2 'Also Err 8
End Sub
There's no error if n1 and n2 are initially declared as Long types. So if you are dealing with large values like pixels and twips, declare variables with type Long or Single.