【问题标题】:Declare a variable as Decimal将变量声明为 Decimal
【发布时间】:2015-09-04 05:09:02
【问题描述】:

我正在优化 VBA 中没有声明任何数据类型的宏,因此编译器将所有内容都笨拙地视为变体。我正在处理科学测量,所以我需要精确度。

我如何声明Dim decAsdf as Decimal(不是那样,而是正确的方式)?

【问题讨论】:

    标签: excel vba excel-2007


    【解决方案1】:

    您不能将变量声明为 Decimal - 您必须使用 Variant(您可以使用 CDec 来使用 Decimal 类型填充它)。

    【讨论】:

    • 例如:Dim v: v = CDec("123456789.123456789")
    • 那么每个小数是在不同的行上声明的吗?
    • 我不明白你的意思。声明是Dim,与任何其他变量类型没有区别。
    • 这是一个正确的例子吗:Dim decMeanComp: decMeanComp = CDec("1234")
    • 是的。只是为了澄清 - 声明和赋值不必在同一行,我不能在评论中发布单独的代码行!
    【解决方案2】:

    要将变量声明为Decimal,首先将其声明为Variant,然后使用CDec 转换为Decimal。监视窗口中的类型为Variant/Decimal

    Considering that programming floating point arithmetic is not what one has studied during Maths classes at school,应尽可能通过转换为十进制来避免常见的陷阱。

    在下面的示例中,我们看到表达式:

    0.1 + 0.11 = 0.21

    TrueFalse,取决于收藏品 (0.1,0.11) 是声明为 Double 还是 Decimal

    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
    

    【讨论】:

      【解决方案3】:

      最好的方法是将变量声明为SingleDouble,具体取决于您需要的精度。数据类型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
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2013-05-28
        • 2012-02-13
        • 1970-01-01
        • 2015-12-31
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多