有人可以解释一下为什么当操作的接收者c
时,下面的代码会在VBA 中产生溢出错误吗?是 Integer
?
Dim a As byte, b As Byte
Dim c As Integer
a = 3: b = 100
c = a * b
或者这是否意味着涉及“字节”变量的每个操作都必须只产生一个介于 0 和 255 之间的结果,而不管接收者变量类型如何?
最佳答案
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
是的,因为字节只保存从 0 到 255 的值,乘以 3 x 100,您正在传递(溢出)它的容量,即使之后您将结果传递给一个整数。
因为您将两个字节相乘,所以 VBA 假设结果也是一个字节。只有在计算之后才会将结果转换为整数。
要解决此问题,您必须转换至少一个变量。这让 VBA 知道它必须为更大的结果腾出空间:
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
关于带有字节变量的 VBA 溢出错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23995459/