长数据类型不在 Excel VBA 中存储长值

Long Data Type Not Storing Long Value in Excel VBA

当我在 excel VBA 中执行下面的代码时,第一个消息框 returns 长值正确但是当我将该值存储在长数据类型和消息框中时,长变量 returns 0 (?!).

Sub Test()

Dim lFileCount As Long
Dim lAdder As Long

lFileCount = 1

MsgBox 0.35! + (0.15! / lFileCount)

lAdder = 0.35! + (0.15! / lFileCount)
MsgBox lAdder
MsgBox Format(lAdder, "0.0")

End Sub

感叹号的原因是我从中推断代码的项目中的longs溢出。如果我删除它们,它不会改变结果。我不知道是什么原因造成的,我的第一个想法是它与变量如何根据操作顺序存储有关,但我没有可行的解决方案。

我很困惑,任何帮助将不胜感激!

Long是整数。

我将 lAdder 更改为 Variant 以收集十进制值:

Sub Test()
    Dim lFileCount As Long
    Dim lAdder As Variant
    lFileCount = 1
    MsgBox 0.35 + (0.15 / lFileCount)
    lAdder = 0.35 + (0.15 / lFileCount)
    MsgBox lAdder
    MsgBox Format(lAdder, "0.0")
End Sub

看起来我对 As Variant 的使用不合适,如对此答案的评论中所示。由于 Double 应该用于小数:

 Sub Test()
    Dim lFileCount As Long
    Dim lAdder As Double
    lFileCount = 1
    MsgBox 0.35 + (0.15 / lFileCount)
    lAdder = 0.35 + (0.15 / lFileCount)
    MsgBox lAdder
    MsgBox Format(lAdder, "0.0")
End Sub

The reason for the exclamation points is due to the longs overflowing in the project I extrapolated the code from. If I remove them it doesn't change the result.

读你说的。两次。您不需要这些 类型提示。 VBA 中的任何浮点文字都是隐含的 Double - 通过使用 ! 类型提示它,你正在使它们成为 Single,这减少了大小和精度您将使用的类型。

稍微研究一下 VBA data types,您会发现 Long 无法保存浮点值。一个Long是一个32位的整数,就是全部。所以这样做:

Dim lAdder As Long

然后这样做:

MsgBox Format(lAdder, "0.0")

没有意义:任何整数值的小数部分始终为 0。

并且 0.35 + 0.15 总是 0.5,转换为 Long 也总是 0:

Debug.Print CLng(0.5) 'prints 0

这就是你在这里所做的,含蓄地:

lAdder = 0.35! + (0.15! / lFileCount)

您正在使用 Double,并将其分配给 Long。结果将是 Long.

声明lAdder As Double,问题解决。

也就是说,删除 l 前缀。它毫无用处,令人困惑,并且散发着 Systems Hungarian 符号的味道,这绝对没有任何用处,只会让您的代码膨胀并使所有内容变得比应有的更难阅读。