Using the immediate window to do some debugging, I came across the following which I have simplified for the purpose of this question:
running this command:
?20000*2
produces an 'overflow' error. Let's assume this is because we haven't declared a data type, and VBE has assumed Integer
- the result falls outside the boundaries of a signed integer and therefore an overflow occurs.
However if I run:
?39999+1
I get 40000
as expected.
Is this because I've initially started with a Long
instead of an Integer
(i.e. 20,000 vs 39,999)? And therefore memory is allocated based on the initial input data rather than the calculation result?
That's correct. VBA will take the largest of the input components and allocate memory for the results. Since both of the components in the first example are Int, that's all you get.
You can use a type declaration character to force the VBE to treat a number as a certain data type
?20000&*2
40000
?20000*2&
40000
In both those examples, the & (Long type declaration character) forces the memory allocation to a Long. It doesn't matter if it's the first component or a later one. I think there are some operations that get forced into particular data types. Exponentiation is one of them.
?2^2^2^2^2^2
4294967296
?typename(2^2^2^2^2^2)
Double
Even though all the components are Integers, the results is a Double - even when it doesn't have to be
?typename(2^2)
Double
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With