user3699486
user3699486

Reputation: 13

VBA overflow error with byte variables

Can someone please explain why the following code would generate an overflow error in VBA when the recipient of the operation c is an Integer?

Dim a As byte, b As Byte  
Dim c As Integer  
a = 3: b = 100  
c = a * b  

or does it mean that every operation involving 'Byte` variables would have to yield only a result be between 0 and 255 regardless of the recipient variable type?

Upvotes: 1

Views: 907

Answers (1)

LimaNightHawk
LimaNightHawk

Reputation: 7083

or does it mean that every operation involving byte variables would have to yield only a result be between 0 and 255 regardless of the recipient variable type

Yes, because Bytes only hold values from 0 to 255, multiplying 3 x 100, you are passing (overflowing) its capacity, even though afterwards you are passing the result into an integer.

Because you are multiplying two Bytes together, VBA assumes the result to be a Byte too. It is only after the calculation that the result is then cast to an integer.

To get around this, you must cast at least one of the variables. This lets VBA know that it must make room for a larger result:

Dim a As Byte, b As Byte
Dim c As Integer
a = 3
b = 100
c = a * CInt(b) ' <-- Cast b as Integer to prevent Overflow error

Upvotes: 4

Related Questions