字节变量的 VBA 溢出错误 [英] VBA overflow error with byte variables

查看:40
本文介绍了字节变量的 VBA 溢出错误的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

谁能解释为什么当操作 c 的接收者是 Integer 时,为什么下面的代码会在 VBA 中产生溢出错误?

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  

或者这是否意味着无论接收者变量类型如何,涉及Byte"变量的每个操作都必须只产生介于 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 之间的结果,而不管接收者变量类型如何

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,你正在传递(溢出)它的容量,即使之后你将结果传递给一个整数.

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.

因为您将两个字节相乘,所以 VBA 假定结果也是一个字节.只有在计算之后,结果才会然后转换为整数.

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.

要解决这个问题,您必须至少转换一个变量.这让 VBA 知道它必须为更大的结果腾出空间:

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

这篇关于字节变量的 VBA 溢出错误的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆