Overflow Error with Byte Data Type when the Value provided within its limits

Viewed 43

for some reason, I'm getting an Overflow error (Runtime error:6) even though the byte data type value is within its limits. Here's the code:

Sub Var_Dec2()
Dim myByt As Byte '0 to 255
myByt = 255
Range("a24").Value = myByt * 1000
End Sub

Please help me understand this!!! thank you

2 Answers

You've defined myByt as Byte, so when you do myByt * 1000 you are getting another Byte number. And it must be a value between 0 and 255.

Edit: Actually, when you multiply 2 defined variables diferent, the output will be the largest type.

myLong = 1000
Range("a24").Value = myByt * 1000 'will raise error
Range("a24").Value = myByt * myLong 'will NOT raise error

UPDATE 2: Found this old question about same issue: VBA overflow error with byte variables

In addition to using a defined variable for the multiplication, you can just cast the byte data into long data for the calculation

Sub Var_Dec2()
    Dim myByt As Byte '0 to 255
    myByt = 255
    Range("A24") = CLng(myByt) * 1000
End Sub
Related