why the code make the error "Overflow"?

V

voda

Sub MyByte()
Dim b1 As Byte, b2 As Byte, i As Long
For b1 = 1 To 200
For b2 = 1 To 200
i = b1 + b2
Next
Next
End Sub
Thanks and regards.
voda
 
P

Peter T

When you process numbers which are entirely bytes the result (or partial
result) will be made as a byte. However if the result is outside the scope
of a byte (0-255) you will get an overflow error.

Here's one way to correct your example
i = CLng(b1) + b2

The following fails because 32000 and 1000 as initially interpreted as
Integers, but 33000 is more than the scope of an Integer
dim i as long
i = 32000 + 1000 ' overflow
i = 32000& + 1000 ' works

Regards,
Peter T
 
D

Dave Peterson

Bytes can range from 0 to 255.

In:
i = b1 + b2
The arithmetic (the righthand side) is done in byte arithmetic. So it blows up
at 256 (b1=56 and b2=200).

If I were you, I'd never use "As Byte" or "As Integer". I'd always use as "As
Long".
 
Top