目录

# FormatNumber 函数 [VBA]

返回数字表达式按特定数字格式表示的字符串。

This constant, function or object is enabled with the statement Option VBASupport 1 placed before the executable program code in a module.

### 语法:

            FormatNumber( expression As Variant, [numDigitsAfterDecimal As Integer], [includeLeadingDigit As Integer], _
                [useParensForNegativeNumbers As Integer], [groupDigits As Integer] ) As String

### 返回值:

String

### 参数:

expression: Required. A numeric expression to be formatted. If expression is a string, then the decimal and thousands separator need to be localized.

「numDigitsAfterDecimal」: 可选。数字表达式，指定小数点后应显示的位数。若忽略，则默认为 -1，即使用用户界面区域的默认设置。

「includeLeadingDigit」: 可选。vbTriState 枚举值，指定小数是否应显示开头的零。

- 「vbTrue 或 -1」: 显示开头的零。

- 「vbFalse or 0」: 不显示开头的零。

- vbUseDefault or -2: Use the user interface locale settings. This is the default when omitted.

「useParensForNegativeNumbers」: 可选。vbTriState 枚举值，指定负数是否应被括号包围。

- 「vbTrue or -1」: 为负数加上括号。

- 「vbFalse or 0」: 不显示括号。

- vbUseDefault or -2: Same as vbFalse. This is the default when omitted.

「groupDigits」: 可选。vbTriState 枚举值，指定要分组的数字 (如每千位)，使用系统区域设置指定的分组分隔符。

- 「vbTrue or -1」: 数位分组。

- 「vbFalse or 0」:数位不分组。

- vbUseDefault or -2: Same as vbFalse. This is the default when omitted.

### 错误代码:

13 数据类型不匹配

### 示例:

            Sub TestFormatNumber
            testName = "Test 1: positive, 2 decimals"
            str2 = "12.20"
            str1 = FormatNumber("12.2", 2, vbFalse, vbFalse, vbFalse)
            msgbox( "FormatNumber returned: " + str1 + ", Expected: " + str2)

            testName = "Test 2: negative, 20 decimals, use leading zero"
            str2 = "-0.20000000000000000000"
            str1 = FormatNumber("-.2", 20, vbTrue, vbFalse, vbFalse)
            msgbox( "FormatNumber returned: " + str1 + ", Expected: " + str2)

            testName = "Test 3: negative, 20 decimals, no leading zero"
            str2 = "-.20000000000000000000"
            str1 = FormatNumber("-0.2", 20, vbFalse, vbFalse, vbFalse)
            msgbox( "FormatNumber returned: " + str1 + ", Expected: " + str2)

            testName = "Test 4: negative, no leading zero, use parens"
            str2 = "(.20)"
            str1 = FormatNumber("-0.2", -1, vbFalse, vbTrue, vbFalse)
            msgbox( "FormatNumber returned: " + str1 + ", Expected: " + str2)

            testName = "Test 5: negative, default leading zero, use parens"
            str2 = "(0.20)"
            str1 = FormatNumber("-0.2", -1, vbUseDefault, vbTrue, vbFalse)
            msgbox( "FormatNumber returned: " + str1 + ", Expected: " + str2)

            testName = "Test 6: group digits"
            str2 = "-12,345,678.00"
            str1 = FormatNumber("-12345678", -1, vbUseDefault, vbUseDefault, vbTrue)
            msgbox( "FormatNumber returned: " + str1 + ", Expected: " + str2)
            End Sub

相关主题

VBA 数学函数