FormatNumber 函数 [VBA]

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

warning

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


语法:

FormatNumber( expression, numDigitsAfterDecimal as Integer, includeLeadingDigit as Integer, useParensForNegativeNumbers as Integer, groupDigits as Integer )

返回值:

字符串

参数:

expression」: 必填。要格式化的数字表达式。

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

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

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

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

错误代码:

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
    

请支持我们!