VBA for...next loop with byte data type not supported?

Viewed 78

Why do I get error 6 "overflow" with this code? I'm confused..

Sub test()
    Dim i as byte
    For i = 3 To 2 step - 1
        Debug.Print i
    Next
End Sub

The same with type integer works.

1 Answers

In this case, the step is also of type Byte and bytes can only be 0 ... 255, hence the overflow. The same occurs if you simply do

dim i as byte
i = -1

or even with

For i = 200 To 255
    Debug.Print i
Next

as, at the end of the last loop, i is incremented in the next statement before doing the comparison (<=255) and this incrementation leads to an overflow error.

Related