The VBA FormatNumber function applies a number format to a numeric expression and returns the result as a string.
The syntax of the function is:
Where the function arguments are:
Expression | - |
The expression that you want to format. |
|||||||||
[NumDigitsAfterDecimal] | - |
An optional numeric value specifying the number of digits that should be displayed after the decimal. If [NumDigitsAfterDecimal] is omitted, it defaults to the value -1, denoting that the computer's regional settings should be used. |
|||||||||
[IncludeLeadingDigit] | - |
An optional vbTriState enumeration value, specifying whether a leading zero should be displayed for fractional values. This can have any of the following values:
If omitted, the [IncludeLeadingDigit] argument is set to vbUseDefault. |
|||||||||
[UseParensForNegativeNumbers] | - |
An optional vbTriState enumeration value, specifying whether negative numbers should be encased in parentheses. This can have any of the following values:
If omitted, the [UseParensForNegativeNumbers] argument is set to vbUseDefault. |
|||||||||
[GroupDigits] | - |
An optional vbTriState enumeration value, specifying whether the number should be grouped (into thousands, etc.), using the group delimiter that is specified on the computer's regional settings. This can have any of the following values:
If omitted, the [GroupDigits] argument is set to vbUseDefault. |
The following example shows how the VBA FormatNumber function can be used to format numeric values. Each example uses different formatting rules.
' Format numeric values in different ways.
Dim num1 As String
Dim num2 As String Dim num3 As String Dim num4 As String
num1 = FormatNumber( 1000000 )
' num1 is now equal to the String "1,000,000.00".
num2 = FormatNumber( 1000000, , , , vbFalse )
' num2 is now equal to the String "1000000.00".
num3 = FormatNumber( 100.55, 0 )
num4 = FormatNumber( -500, , , vbTrue )' num3 is now equal to the String "101". ' num4 is now equal to the String "(500.00)". |
Note that in the above calls to the FormatNumber function:
Note also, that in each case, the result that is returned from the FormatNumber function is a String data type.
If the Expression that is supplied to the FormatNumber function is a text string that cannot be converted into a numeric value, you will get the error: