简体   繁体   English

使用Excel 2007+ VBA和单元格的NumberFormat属性设置数字文本的格式

[英]Using Excel 2007+ VBA and a Cell's NumberFormat Property to Format Number Text

I would like to use VBA and a cell's format when displaying related numbers with MsgBox and/or in concatenated text strings. 在使用MsgBox和/或串联文本字符串显示相关数字时,我想使用VBA和单元格格式。

I have tried using the cell's NumberFormat property but get unusable results... 我尝试使用单元格的NumberFormat属性,但得到不可用的结果...

eg the following sample code should tell a user to charge $4.50 for lemonade that is marked up 150% above cost... 例如,以下示例代码应告诉用户,对标价超出成本150%的柠檬水收取4.50美元的费用...

Private Sub Worksheet_SelectionChange(ByVal Target As Range)
    MsgBox "I should charge " & Format(Range("a3").Value * 1.5, Range("a3").NumberFormat) & " for this lemonade."
End Sub

...results in... ...结果是...

当源单元格未格式化并格式化为货币时的示例输出...

There are two scenarios displayed: the first is an unformatted cell; 显示了两种情况:第一种是未格式化的单元格;第二种是未格式化的单元格。 the second is a currency-formatted cell. 第二个是货币格式的单元格。 I would like my code to accommodate any valid number format, including custom formats. 我希望我的代码能够容纳任何有效的数字格式,包括自定义格式。

As long as you use US regional settings, you can use Application.Text instead of Format : 只要您使用美国区域设置,就可以使用Application.Text代替Format

Private Sub Worksheet_SelectionChange(ByVal Target As Range)
    MsgBox "I should charge " & Application.Text(Range("a3").Value * 1.5, Range("a3").NumberFormat) & " for this lemonade."
End Sub

for example. 例如。 If you don't have US settings, you'll still need to work around any localised currency formats. 如果您没有美国设置,则仍然需要解决所有本地化的货币格式。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM