[英]x = x + y formula returning 0 in Excel VBA
While running the following code the variable intEarn does not change from 0 when adding on a formula onto itself in the style of intEarn = intEarn + (...)
. 在运行以下代码时,以
intEarn = intEarn + (...)
的样式向自身添加公式时,变量intEarn不会从0更改。
I have placed message boxes throughout the code to see exactly what is being computed each time and for whatever reason it seems that the intEarn = intEarn + (...)
always results in 0 no matter what is in the (...)
. 我已经把消息框整个代码,看看到底什么是被计算每次以任何理由似乎
intEarn = intEarn + (...)
结果总是在0不管是在(...)
Dim ovr As Range
Set ovr = cells.Find("Overview").Offset(2, 0)
Dim intEarn As Long
intEarn = 0
...
x = 0
Do until IsEmpty(ovr.Offset(x, 0))
'The following line results in 0
intEarn = intEarn + (ovr.Offset(x, 0).Offset(0, 1).Value * ovr.Offset(x,0).Offset(0, 2).Value)
'While the next line of code results in the proper number
MsgBox ("Correct: " & ovr.Offset(x, 0).Offset(0, 1).Value * ovr.Offset(x, 0).Offset(0, 2).Value)
x = x + 1
Loop
I expected the first output of intEarn = intEarn + (ovr.Offset(x, 0).Offset(0, 1).Value * ovr.Offset(x,0).Offset(0, 2).Value
to equal 0.327 since ovr.Offset(x, 0).Offset(0, 1).Value
= 1090 and ovr.Offset(x, 0).Offset(0, 2).Value
= .03% . 我期望
intEarn = intEarn + (ovr.Offset(x, 0).Offset(0, 1).Value * ovr.Offset(x,0).Offset(0, 2).Value
一个输出等于0.327,因为ovr.Offset(x, 0).Offset(0, 1).Value
= 1090和ovr.Offset(x, 0).Offset(0, 2).Value
= .03% 。
Dim intEarn As Long
Long
is a 32-bit integer type, it doesn't deal with decimals. Long
是32位整数类型,它不处理小数。 So when the right-hand side of the assignment evaluates to 0.327, VBA merrily performs a narrowing conversion from Double
to Long
, and you get 0
. 因此,当赋值的右侧求值为0.327时,VBA就会轻松地执行从
Double
到Long
的变窄转换,并且得到0
。
Declare it as a Double
, and the implicit narrowing conversion will no longer happen, the decimals will be preserved, and the code should run as intended. 将其声明为
Double
,隐式变窄转换将不再发生,小数点将被保留,并且代码应按预期运行。
Except int
is a misleading prefix for a Double
. int
是Double
的误导前缀。 Better avoid encoding a data type in the name. 最好避免在名称中编码数据类型。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.