Saturday, July 23, 2016

How to use the FORMAT Function with Strings (VBA)

Description

The Microsoft Excel FORMAT function takes a string expression and returns it as a formatted string.

Syntax

The syntax for the FORMAT function in Microsoft Excel is:
Format ( expression, [ format ] )

Parameters or Arguments

expression
The string value to format.
format
Optional. It is the format to apply to the expression. You can either define your own format or use one of the named formats that Excel has predefined such as:
FormatExplanation
General NumberDisplays a number without thousand separators.
CurrencyDisplays thousand separators as well as two decimal places.
FixedDisplays at least one digit to the left of the decimal place and two digits to the right of the decimal place.
StandardDisplays the thousand separators, at least one digit to the left of the decimal place, and two digits to the right of the decimal place.
PercentDisplays a percent value - that is, a number multiplied by 100 with a percent sign. Displays two digits to the right of the decimal place.
ScientificScientific notation.
Yes/NoDisplays No if the number is 0. Displays Yes if the number is not 0.
True/FalseDisplays False if the number is 0. Displays True if the number is not 0.
On/OffDisplays Off if the number is 0. Displays On is the number is not 0.
General DateDisplays date based on your system settings
Long DateDisplays date based on your system's long date setting
Medium DateDisplays date based on your system's medium date setting
Short DateDisplays date based on your system's short date setting
Long TimeDisplays time based on your system's long time setting
Medium TimeDisplays time based on your system's medium time setting
Short TimeDisplays time based on your system's short time setting

Applies To

  • Excel 2016, Excel 2013, Excel 2011 for Mac, Excel 2010, Excel 2007, Excel 2003, Excel XP, Excel 2000

Type of Function

  • VBA function (VBA)

Example (as VBA Function)

The FORMAT function can only be used in VBA code in Microsoft Excel.
Let's look at some Excel FORMAT function examples and explore how to use the FORMAT function in Excel VBA code:
Format("210.6", "#,##0.00")
Result: '210.60'

Format("210.6", "Standard")
Result: '210.60'

Format("0.981", "Percent")
Result: '98.10%'

Format("1267.5", "Currency")
Result: '$1,267.50'

Format("Sep 3, 2003", "Short Date")
Result: '9/3/2003'
For example:
Dim LValue As String

LValue = Format("0.981", "Percent")
In this example, the variable called LValue would now contain the value of '98.10%'.