在 Excel VBA 中使用数字格式
    
    
            Glen Alfaro
    2023年1月30日
    
    VBA
    VBA Number Format
    
 
数字在我们的日常生活中以不同的形式出现。我们有日期、价格、百分比、分数、小数等。它们可能看起来都不同,但它们都表示一个值。
与 Excel 相同,我们可以处理不同格式的数字。我们可以在处理时间和日期时使用 Date 和 Time 数据类型,而在处理百分比时我们可以使用 Percent。
本文将演示 NumberFormat 属性,以帮助我们在 Excel VBA 实践中充分利用和处理数字。
在数值 VBA 上实现 NumberFormat 属性
本节使用 NumberFormat 属性更改单元格中的数字格式。
语法:
Range.NumberFormat = [FormatCodes]
参数:
| Range | 要格式化的范围 | 
| [FormatCodes] | 预先确定的字符串,它将表示要使用的数字格式类型。 | 
[格式代码] 矩阵:
| 格式名称 | 格式代码 | 例子 | 描述 | 
| —————– | ——————————————————– | —————– | —————————————————— | 
| 常规 | General | 1234567.89 | 显示没有特定格式的数字 | 
| 货币 | $#,##0.00 | $1,234,567.89 | 显示为一般货币价值 | 
| 数字 | 0 | 1234567.89 | 格式将完全按原样显示数字 | 
| 科学计数 | 0.00E+00 | 1.23E+06 | 将数字转换为指数格式 | 
| 会计 | _($* #,##0.00_);_($* (#,##0.00);_($* ""-""??_);_(@_) | $123.00 | display the number used in 会计 | 
| 日期 | m/d/yy | 11/23/2021 | 显示日期和时间序列号 | 
| 时间 | [$-F400]h:mm:ss am/pm | 12:00:03 上午 | 显示日期和时间序列号 | 
| 百分比 | 0.00% | 5.23 % | 以百分比形式显示值 | 
| 分数 | # ?/? | 1/4 | 将值显示为小数形式 | 
| 特殊 | ;; | 000-00-0000 | 用于列表和数据库值的格式 | 
Sheet1 虚拟工作表将是以下示例代码中所有示例中使用的引用值。
表 1:
 |    A    |      B      |      C    |
1| 1234.56 | 11/23/2021  | 93249812  |
2| 5       | 0.00004     | 0.25      |
下面的代码块将输出 General 格式:
Sub FormatGeneral()
Range("A1").NumberFormat = "General"
Debug.Print Range("A1").Text
End Sub
FormatGeneral 输出:
1234.56 
下面的代码块将输出 Currency 格式:
Sub FormatCurrency()
Range("C1").NumberFormat = "$#,##0.00"
Debug.Print Range("C1").Text
End Sub
通用输出:
$93,249,812.00
下面的代码块将输出科学格式:
Sub FormatScientific()
Range("C1").NumberFormat = "0.00E+00"
Debug.Print Range("C1").Text
End Sub
FormatScientific 输出:
9.32E+07
下面的代码块将输出 Accounting 格式:
Sub FormatAccounting()
Range("A1").NumberFormat = "_($* #,##0.00_);_($* (#,##0.00);_($* ""-""??_);_(@_)"
Debug.Print Range("A1").Text
End Sub
FormatAccounting 输出:
 $ 1,234.56 
下面的代码块将输出日期格式:
Sub FormatDate()
Range("A2").NumberFormat = "m/d/yy"
Debug.Print Range("A2").Text
End Sub
FormatDate 输出:
1/5/00
下面的代码块将输出时间格式:
Sub FormatTime()
Range("B2").NumberFormat = "$-F400]h:mm:ss am/pm"
Debug.Print Range("B2").Text
End Sub
FormatTime 输出:
12:00:03 AM
下面的代码块将输出百分比格式:
Sub FormatPercentage()
Range("A1").NumberFormat = "0.00%"
Debug.Print Range("A1").Text
End Sub
FormatPercentage 输出:
123456.00%
下面的代码块将输出 Fraction 格式:
Sub FormatFraction()
Range("C2").NumberFormat = "# ?/?"
Debug.Print Range("C2").Text
End Sub
FormatFraction 输出:
1/4
获取 VBA 范围使用的 NumberFormat 类型
我们在上面的例子中返回了指定范围的格式化值。我们将在本节中获取指定范围内使用的格式类型。
语法:
Range.NumberFormat
参数:
| Range | 获取格式类型的单元格范围 | 
仍然参考 Sheet1,下面的示例代码块将演示返回指定范围使用的格式类型。
Sub GetFormattingType()
Debug.Print Range("B1").NumberFormat
End Sub
GetFormattingType 输出:
m/d/yyyy
        Enjoying our tutorials? Subscribe to DelftStack on YouTube to support us in creating more high-quality video guides. Subscribe