我正在优化一个在VBA中没有声明任何数据类型的宏,所以所有的东西都被编译器笨拙地当作变体处理。我正在处理科学测量,所以我需要精确度。
我应该如何声明
我应该如何声明
Dim decAsdf as Decimal
(不是这样,而是正确的方式)?Dim decAsdf as Decimal
(不是这样,而是正确的方式)?您无法将变量声明为 Decimal
- 您必须使用 Variant
(但是您可以使用 CDec
将其填充为 Decimal
类型)。
Decimal
,需先声明为Variant
,然后使用CDec
进行转换。在监视窗口中类型应为Variant/Decimal
:
考虑到编程浮点算术不是我们在学校数学课上学习的内容,因此应尽可能避免常见陷阱,而在可能的情况下进行十进制转换,参考文献:Goldberg的文章。0.1 + 0.11 = 0.21
,取决于收集品(0.1、0.11)是否声明为Double
或Decimal
,结果可能为True
或False
:Public Sub TestMe()
Dim preciseA As Variant: preciseA = CDec(0.1)
Dim preciseB As Variant: preciseB = CDec(0.11)
Dim notPreciseA As Double: notPreciseA = 0.1
Dim notPreciseB As Double: notPreciseB = 0.11
Debug.Print preciseA + preciseB
Debug.Print preciseA + preciseB = 0.21 'True
Debug.Print notPreciseA + notPreciseB
Debug.Print notPreciseA + notPreciseB = 0.21 'False
End Sub
Single
或Double
。数据类型Single
使用4个字节,范围为-3.402823E38至1.401298E45。Double
使用8个字节。Dim decAsdf as Single
或者
Dim decAsdf as Double
Sub doubleDataTypeExample()
Dim doubleTest As Double
doubleTest = 0.0000045 * 0.005 * 0.01
MsgBox "doubleTest = " & doubleTest
End Sub
Dim v: v = CDec("123456789.123456789")
- Rory