Strange Overflow!

P

Peter R Hawkes

The following code;

Sub Test()

Dim x As Long

x = 100 * 329

End Sub

results in the following error;

RunTime Error '6'

Overflow

.... but why!?
 
A

Andy Pope

Hi,

The help file explains the problem.

Overflow (Error 6)
You attempt to use a number in a calculation, and that number is coerced
into an integer, but the result is larger than an integer. For example:
Dim x As Long
x = 2000 * 365 ' Error: Overflow
To work around this situation, type the number, like this:

Dim x As Long
x = CLng(2000) * 365

Cheers
Andy
 
K

Karl E. Peterson

Peter said:
I misinterpreted the Help file! Thank you.

I'm not sure this is explained all that well in the Help file? The thing to
always keep in mind is that VB/VBA will always use the "smallest" datatype
it thinks it can to calculate intermediate results. IOW, if you're
multiplying two Integer values, VB/VBA will attempt to store the result in
another 2-byte Integer before assignment. If you multiply an Integer and a
Long, the intermediate storage allocated will be a 4-byte Long. This is
actually a Good Thing, because were this not the case, you'd essentially be
asking VB to consider far more possibilities before doing each math
operation, thus frequently slowing down the entire process needlessly. As
it is, *you* make the call on datatype, and live with the
results/consequences.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top