Overflow

TedMartin

Registered User.
Local time
Today, 21:07
Joined
Sep 29, 2003
Messages
76
I have some code that is puzzling me.

Dim iCycle as Long
Dim iStep as Integer

iStep = 10

more code ...

If iCycle >= 10 * 60 * 1000 / iStep then
'Do something
end if

I get a Error 6 overflow on the IF line of code.

If iCycle >= 10 * 60 * (1000 / iStep) then

I don't understand as 10*60*1000 = 600,000 which is well within the Long range.

Anyt thoughts would be welcome.


However it does not erro if the line of code is
 
Looks like you got cut off there in mid sentence.

As for the overflow, try changing iStep to a LONG instead of Integer and see what happens. You also have to take into account zeroes if iStep is a zero it can't be used as a divisor.
 
The problem here is that VBA interprets each of these numbers as integers
Code:
10 * 60 * 1000
and so tries to use integers to do the math, but the biggest integer is 32767. For example, type
Code:
? 32767 + 1
in the immediate window and you'll get an overflow error. If you explicity indicate a long for one of the numbers the problem goes away, because VBA uses Longs to do the math ...
Code:
10& * 60 * 1000  [COLOR="Green"]'the ampersand declares the number as a long[/COLOR]
clng(10) * 60 * 1000  [COLOR="Green"]'or use the CLng() function[/COLOR]
 
Got it - thanks. I can rest east now I understand why.
 
Sorry Bob; my post should have read:

I have some code that is puzzling me.

Dim iCycle as Long
Dim iStep as Integer

iStep = 10

more code ...

If iCycle >= 10 * 60 * 1000 / iStep then
'Do something
end if

I get a Error 6 overflow on the IF line of code.


However it does not error if the line of code is:

If iCycle >= 10 * 60 * (1000 / iStep) then

I don't understand as 10*60*1000 = 600,000 which is well within the Long range.

Any thoughts would be welcome.
 

Users who are viewing this thread

Back
Top Bottom