【问题标题】:How to retain the NumberFormat when converting numbers to a string in Excel VBA?在 Excel VBA 中将数字转换为字符串时如何保留 NumberFormat?
【发布时间】:2016-03-09 02:35:17
【问题描述】:

考虑以下代码:

Sub CombineNumbersToASTring()

' force Excel to show two decimals, even when there are trailing zeros
Range("A1", "B1").NumberFormat = "0.00"

' give some values to the previously mentioned cells
Cells(1, 1).Value = 0.1
Cells(1, 2).Value = 0.2

' combine the previous two values into one cell
Cells(1, 3).Value = "(" & Cells(1, 1).Value & ", " & Cells(1, 2).Value & ")"

End Sub

结果错误

0.10 0.20 (0.1, 0.2)

虽然应该是

0.10 0.20 (0.10, 0.20)

那么,在 Excel VBA 中转换为字符串时如何保留 NumberFormat? CStr 方法似乎不起作用。

(编辑:我还要在这里补充一点,在我的较大代码中,小数位数从一个单元格变为另一个单元格,因此在编写 VBA 代码时无法预先知道小数位。)

【问题讨论】:

    标签: vba excel


    【解决方案1】:

    至少有两种方法可以实现这一目标。

    1. 使用.Text 属性。
      Cells(1,3).Value = "(" & Cells(1,1).Text & ", " & Cells(1,2).Text & ")"
    2. 在单元格中使用公式(1,3)
      =CONCATENATE("(",TEXT(A1,"0.00"),", ",TEXT(B1,"0.00"),")")

    【讨论】:

    • 第一个解决方案适合我的需求,我确认它就像一个魅力。疯狂的解决方案是多么简单。此解决方案不需要事先了解小数位。非常感谢,确实。
    【解决方案2】:

    我认为您需要在您的值周围使用带有“0.00”的格式,例如:

    Cells(1, 3).Value = "(" & Format(Cells(1, 1).Value, "0.00") & ", " & Format(Cells(1, 2).Value, "0.00") & ")"
    

    【讨论】:

    • 是的,您的解决方案适用于我最初写的问题。我忘了提到小数位在我的大代码中不是静态的;我现在已将其添加到我的问题中。但是,无论如何,非常感谢您,并为原始问题提供有效的解决方案 +1。 (PatricK 的上述解决方案即使在更改小数位时也有效。)
    【解决方案3】:

    尝试将数字格式范围扩展到 C1 列(单元格(1,3)): Range("A1", "C1").NumberFormat = "0.00"

    【讨论】:

      猜你喜欢
      • 2011-11-28
      • 2012-07-20
      • 1970-01-01
      • 2022-01-22
      • 2017-01-28
      • 1970-01-01
      • 1970-01-01
      • 2014-04-16
      • 2016-02-10
      相关资源
      最近更新 更多