why the code make the error "Overflow"?

  • Thread starter Thread starter voda
  • Start date Start date
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
 
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
 
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".
 
voda said:
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
 

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

Back
Top