VBAfor…不支持字节数据类型的下一个循环?
为什么此代码会出现错误 6“溢出”?我糊涂了..
Sub test()
Dim i as byte
For i = 3 To 2 step - 1
Debug.Print i
Next
End Sub
与整数类型相同。
回答
在这种情况下,step也是类型Byte和字节只能是 0 ... 255,因此溢出。如果您只是这样做,也会发生同样的情况
dim i as byte
i = -1
甚至与
For i = 200 To 255
Debug.Print i
Next
因为,在最后一个循环结束时,在进行比较之前i的next语句中递增( <=255),这种递增导致溢出错误。
- @Pᴇʜ the only good reason to use bytes is when converting strings to byte, since then the operations are numeric and therefore faster (for example implementing the levenshtein distance).
- Nice answer. Good addition to this is: [Why Use Integer Instead of Long?](https://stackoverflow.com/questions/26409117/why-use-integer-instead-of-long/26409520#26409520). This is very likely to happen with `Bytes` too, so there is no good reason to use `Byte` or `Integer` at all in VBA.