Using the VBA Format Function

Currencies and numbers being displayed on a board

Contents

Short introduction to strings

A string is a sequence or group of characters of any length that may or may not have a semantic meaning in language. It can consist of several characters like numbers, letters in both lowercase and uppercase, punctuation, and symbols.

Examples of strings:

1. “Testme123”

2. “Daniel Dozen”

3. “Please enter your name”

4. “Christmas falls on 25th December of every year”

5. “@$#%$%^”

6. “234325fdgdgfd”

Formatting a string

From the above examples we can infer that each character in a string can be a unique datatype, such as “lowercase letter,” “number,” “uppercase letter,” “symbol,” or “punctuation .” In your programmin,g there may be situations you need the string to be a particular format.

For example:

  1. A textbox might expect date to be entered in exactly “mm-dd-yyyy” format.
  2. Numbers entered might need to be displayed along with a currency symbol.
  3. The percentage symbol can be used along with numbers to indicate values like an interest rate.
  4. Decimals can be used with numbers for easy reading.

This formatting can be done using the “Format” functions offered by Visual Basic for Applications.

The Format function

This function offered by the VBA library can be categorized as a string or date function. It converts the given expression to the expected format and returns it as a string.

Syntax

Format ( < string expression > , [ format ] )

Where

< string expression > is the string that needs to be formatted and

[ format ] is format that needs to be applied to the specified string expression. This is an optional parameter, so it’s enclosed with square brackets.

The format parameter can either be a user-defined format or it can be a named format predefined by Excel. Here are some named formats which are provided by MS Excel.

FormatExplanation
GeneralThis is the default number format that MS Excel applies if we simply type a number. In most of the cases, the numbers which are formatted with the “General” format are displayed the same way we type them. However, if the width of the cell is not sufficient to display the entire number, the “General” format rounds off the numbers with decimals. This number format also uses “scientific  notation” (exponential form) for high-value or large numbers that have 12 or more digits.
CurrencyThis is used for monetary values and displays the currency symbol with numbers. The default currency symbol used is “$”. There are options to specify the number of decimal places that we want to use. For example, we may want to use a thousands separator. We can also specify if we want to display number is negative depending on their value.
FixedThis format displays at least 1 digit to the left side of the decimal place and 2 digits to the right side of the decimal place.
StandardThis format displays the thousand separators, at least 1 digit to the left side of the decimal place, and 2 digits to the right side of the decimal place.
PercentThis format displays a percent value – (ie), a number divided by 100 with a % sign. It displays two digits to the right of the decimal place.
ScientificIndicates scientific notation. It’s a number in exponential notation, which replaces a part of the number with “E+n”, where E (stands for Exponent) and multiplies the preceding number by “10” to the nth power. For example, a two decimal Scientific format displays 12345678901 as 1.23E+10, which is 1.23 times 10 to the 10th power. We can specify the number of decimal places that we want to use.
Yes/NoThis format displays “No” if the number is 0 and “Yes” if the number is not 0.
True/FalseThis format displays “False” if the number is 0 and “True” if the number is not 0.
On/OffThis format displays “Off” if the number is 0 and “On” if the number is not 0.
General DateThis format displays date and time serial numbers as date values, based on the type and location we specify. Date formats which begin with an asterisk symbol (*) respond to changes in the regional date and time settings already set in the system’s Control Panel. Formats which do not have an asterisk are not affected by settings in the Control Panel.
Long DateThis format displays a date value based on long date setting of our system
Medium DateThis format displays a date value based on meduim date setting of our system
Short DateThis format displays a date value based on short date setting of our system
TimeThis format displays date and time serial numbers as time values, depending on the type and location we specify. Time formats that begin with an asterisk symbol (*) respond to changes in the regional date and time settings already set in the system’s Control Panel. Formats which do not have an asterisk are not affected by settings in the Control Panel.
Long TimeThis format displays a date value based on long time setting of our system
Medium TimeThis format displays a date value based on meduim time setting of our system
Short TimeThis format displays a date value based on short time setting of our system
NumberThis is used in general to display numbers. We can specify the number of decimal places that we would like to use. For example , we may want to use a thousands separator. We can also specify if we want to display number is negative depending on their value.
AccountingThis is also used for monetary values . It aligns the decimal points of numbers and currency symbols in a column.
FractionIt displays a number as a fraction depending on the type of fraction we specify.

Examples using the Format function

Using a custom format to format numbers

Sub format_demo()

' declare variable
Dim str_num

' use the format function and assign value
str_num = Format("510.3", "#,##0.00")

' print the value - it should be '510.30'
Debug.Print str_num

End Sub

Predefined formatting used on numbers

This example covers formatting numbers with percentage, currency and decimals.

Sub format_demo_predef()


'declare variables
Dim str_std, str_per, str_cur, str_shdt

'Assign values using the format function
str_std = Format("611.6", "Standard")
str_per = Format("0.982", "Percent")
str_cur = Format("1369.5", "Currency")

'Print the results
Debug.Print str_std ' Result should be : '611.60'
Debug.Print str_per ' Result should be : '98.20%'
Debug.Print str_cur ' Result should be : '$1,369.50' provided a currency symbol is already set.
End Sub

Sample program to show the format function to display dates

This program displays dates in both short date and long date format. There are some predefined formats the user may be interested in.

Sub format_demo_predef()
' declare variables
Dim str_shdt, str_lgdt

' Assign values using the format function
str_shdt = Format("Sep 9, 2013", "Short Date")
str_lgdt = Format("Sep 9, 2013", "Long Date")

' Print the results
Debug.Print str_shdt ' Result should be : '09-09-2013' ( depends on system setting in control panel )
Debug.Print str_lgdt ' Result should be : '09 September 2013' ( depends on system setting in control panel )

End Sub

Conclusion

The format function can be widely used to display data (strings, numbers, or a combination of both ) the way we want. There may be scenarios that use queries to store or retrieve data from backend and compare it with some other data that is displayed on user forms or webpages.

These comparisons can result in failures even if the data match, just because the format of data being compared is different. In such situations it is a good idea to use this Format function and convert the data that’s being compared to a common format. This will provide you with more reliable results.

Leave a Reply

Your email address will not be published. Required fields are marked *