【问题标题】:VBA Strings without Dollar Signs没有美元符号的 VBA 字符串
【发布时间】:2019-01-25 15:48:20
【问题描述】:

我正在学习 VBA,当 VBA 与添加字符串交互时,我注意到一个奇怪的怪癖。当您采用两种版本的代码(使用此处交换的注释部分更改注释部分)时,一个输出带有美元符号的字符串,一个则没有。有人知道这是一个错误还是计划升级?

Option Explicit
Sub CalcCost()
Dim curSalesPrice As Currency
Dim curTotalCost As Currency
Dim sngSalesTax As Single
Dim strMessage As String

 curSalesPrice = 35
 sngSalesTax = 0.085

    Range("A1:B8").ClearContents
    Range("A1").Value = "The cost of the calculator"
    Range("A4").Value = "Price"
    Range("B4").Value = curSalesPrice
    Range("A5").Value = "SalesTax"
    Range("A6").Value = "Cost"
    Range("B5").Value = curSalesPrice * sngSalesTax

    'curTotalCost = curSalesPrice + (curSalesPrice * sngSalesTax)
    curTotalCost = Format(curSalesPrice + (curSalesPrice * sngSalesTax), "Currency") 'swap here


    'strMessage = "The calculator total is " & Format(curTotalCost, "Currency")
    strMessage = "The calculator total is " & curTotalCost 'swap here

    Range("A8").Value = strMessage
    Range("B6").Value = curTotalCost

End Sub

【问题讨论】:

标签: excel vba


【解决方案1】:

FormatVBA.Strings模块中定义的VBA标准库函数;它返回给定表达式的String representation,格式为指定:这样做没有意义:

Dim foo As Currency ' a numeric data type...
foo = Format(123, "Currency") ' ...assigned to a string representation of a numeric value

但这在这里完全有意义:

Dim msg As String
msg = Format(123, "Currency")

现在,一个单元格的 不同于它的 文本表示。不是因为你在一个单元格中看到$123.00,那个单元格的$123.00(一个String);那是单元格的Text,但它的Value 很可能是123Double),它的NumberFormat$#0.00

您希望使用数字数据类型来执行操作,并且仅当您需要使这些数字值“漂亮”以进行显示时才使用Format。避免对字符串进行算术运算:虽然 可能 起作用,但它也 可能 失败,这取决于字符串的格式和系统语言环境:VBA 需要进行隐式类型执行此类操作的转换,以及隐式转换需要做出许多(有时是错误的)假设。

将数值写入工作表单元格时,请写入数值,而不是它们的字符串表示形式(日期也是如此。尤其是日期,实际上)。代替Format-ing 值,在需要格式化的单元格中为Range.NumberFormat 指定格式字符串。这样,Excel 仍然可以理解这些数值,并且仍然可以正确执行,例如求和运算。

代码完全按照指定和预期工作。

【讨论】:

    猜你喜欢
    • 2015-08-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-04-25
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多