In this Article
- Formatting Numbers in Excel VBA
- How to Use the Format Function in VBA
- Creating a Format String
- Using a Format String for Alignment
- Using Literal Characters Within the Format String
- Use of Commas in a Format String
- Creating Conditional Formatting within the Format String
- Using Fractions in Formatting Strings
- Date and Time Formats
- Predefined Formats
- General Number
- Currency
- Fixed
- Standard
- Percent
- Scientific
- Yes/No
- True/False
- On/Off
- General Date
- Long Date
- Medium Date
- Short Date
- Long Time
- Medium Time
- Short Time
- Dangers of Using Excel’s Pre-Defined Formats in Dates and Times
- User-Defined Formats for Numbers
- User-Defined Formats for Dates and Times
Formatting Numbers in Excel VBA
Numbers come in all kinds of formats in Excel worksheets. You may already be familiar with the pop-up window in Excel for making use of different numerical formats:
Formatting of numbers make the numbers easier to read and understand. The Excel default for numbers entered into cells is ‘General’ format, which means that the number is displayed exactly as you typed it in.
For example, if you enter a round number e.g. 4238, it will be displayed as 4238 with no decimal point or thousands separators. A decimal number such as 9325.89 will be displayed with the decimal point and the decimals. This means that it will not line up in the column with the round numbers, and will look extremely messy.
Also, without showing the thousands separators, it is difficult to see how large a number actually is without counting the individual digits. Is it in millions or tens of millions?
From the point of view of a user looking down a column of numbers, this makes it quite difficult to read and compare.
In VBA you have access to exactly the same range of formats that you have on the front end of Excel. This applies to not only an entered value in a cell on a worksheet, but also things like message boxes, UserForm controls, charts and graphs, and the Excel status bar at the bottom left hand corner of the worksheet.
The Format function is an extremely useful function in VBA in presentation terms, but it is also very complex in terms of the flexibility offered in how numbers are displayed.
How to Use the Format Function in VBA
If you are showing a message box, then the Format function can be used directly:
MsgBox Format(1234567.89, "#,##0.00")
This will display a large number using commas to separate the thousands and to show 2 decimal places. The result will be 1,234,567.89. The zeros in place of the hash ensure that decimals will be shown as 00 in whole numbers, and that there is a leading zero for a number which is less than 1
The hashtag symbol (#) represents a digit placeholder which displays a digit if it is available in that position, or else nothing.
You can also use the format function to address an individual cell, or a range of cells to change the format:
Sheets("Sheet1").Range("A1:A10").NumberFormat = "#,##0.00"
This code will set the range of cells (A1 to A10) to a custom format which separates the thousands with commas and shows 2 decimal places.
If you check the format of the cells on the Excel front end, you will find that a new custom format has been created.
You can also format numbers on the Excel Status Bar at the bottom left hand corner of the Excel window:
Application.StatusBar = Format(1234567.89, "#,##0.00")
You clear this from the status bar by using:
Application.StatusBar = ""
Creating a Format String
This example will add the text ‘Total Sales’ after each number, as well as including a thousands separator
Sheets("Sheet1").Range("A1:A6").NumberFormat = "#,##0.00"" Total Sales"""
This is what your numbers will look like:
Note that cell A6 has a ‘SUM’ formula, and this will include the ‘Total Sales’ text without requiring formatting. If the formatting is applied, as in the above code, it will not put an extra instance of ‘Total Sales’ into cell A6
Although the cells now display alpha numeric characters, the numbers are still present in numeric form. The ‘SUM’ formula still works because it is using the numeric value in the background, not how the number is formatted.
The comma in the format string provides the thousands separator. Note that you only need to put this in the string once. If the number runs into millions or billions, it will still separate the digits into groups of 3
The zero in the format string (0) is a digit placeholder. It displays a digit if it is there, or a zero. Its positioning is very important to ensure uniformity with the formatting
In the format string, the hash characters (#) will display nothing if there is no digit. However, if there is a number like .8 (all decimals), we want it to show as 0.80 so that it lines up with the other numbers.
By using a single zero to the left of the decimal point and two zeros to the right of the decimal point in the format string, this will give the required result (0.80).
If there was only one zero to the right of the decimal point, then the result would be ‘0.8’ and everything would be displayed to one decimal place.
Using a Format String for Alignment
We may want to see all the decimal numbers in a range aligned on their decimal points, so that all the decimal points are directly under each other, however many places of decimals there are on each number.
You can use a question mark (?) within your format string to do this. The ‘?’ indicates that a number is shown if it is available, or a space
Sheets("Sheet1").Range("A1:A6").NumberFormat = "#,##0.00??"
This will display your numbers as follows:
All the decimal points now line up underneath each other. Cell A5 has three decimal places and this would throw the alignment out normally, but using the ‘?’ character aligns everything perfectly.
Using Literal Characters Within the Format String
You can add any literal character into your format string by preceding it with a backslash ().
Suppose that you want to show a particular currency indicator for your numbers which is not based on your locale. The problem is that if you use a currency indicator, Excel automatically refers to your local and changes it to the one appropriate for the locale that is set on the Windows Control Panel. This could have implications if your Excel application is being distributed in other countries and you want to ensure that whatever the locale is, the currency indicator is always the same.
You may also want to indicate that the numbers are in millions in the following example:
Sheets("Sheet1").Range("A1:A6").NumberFormat = "$#,##0.00 m"
This will produce the following results on your worksheet:
In using a backslash to display literal characters, you do not need to use a backslash for each individual character within a string. You can use:
Sheets("Sheet1").Range("A1:A6").NumberFormat = "$#,##0.00 mill"
This will display ‘mill’ after every number within the formatted range.
You can use most characters as literals, but not reserved characters such as 0, #,?
Use of Commas in a Format String
We have already seen that commas can be used to create thousands separators for large numbers, but they can also be used in another way.
By using them at the end of the numeric part of the format string, they act as scalers of thousands. In other words, they will divide each number by 1,000 every time there is a comma.
In the example data, we are showing it with an indicator that it is in millions. By inserting one comma into the format string, we can show those numbers divided by 1,000.
Sheets("Sheet1").Range("A1:A6").NumberFormat = "$#,##0.00,m"
This will show the numbers divided by 1,000 although the original number will still be in background in the cell.
If you put two commas in the format string, then the numbers will be divided by a million
Sheets("Sheet1").Range("A1:A6").NumberFormat = "$#,##0.00,,m"
This will be the result using only one comma (divide by 1,000):
VBA Coding Made Easy
Stop searching for VBA code online. Learn more about AutoMacro — A VBA Code Builder that allows beginners to code procedures from scratch with minimal coding knowledge and with many time-saving features for all users!
Learn More
Creating Conditional Formatting within the Format String
You could set up conditional formatting on the front end of Excel, but you can also do it within your VBA code, which means that you can manipulate the format string programmatically to make changes.
You can use up to four sections within your format string. Each section is delimited by a semicolon (;). The four sections correspond to positive, negative, zero, and text
Range("A1:A7").NumberFormat = "#,##0.00;[Red]-#,##0.00;[Green] #,##0.00;[Blue]”
In this example, we use the same hash, comma, and zero characters to provide thousand separators and two decimal points, but we now have different sections for each type of value.
The first section is for positive numbers and is no different to what we have already seen previously in terms of format.
The second section for negative numbers introduces a color (Red) which is held within a pair of square brackets. The format is the same as for positive numbers except that a minus (-) sign has been added in front.
The third section for zero numbers uses a color (Green) within square brackets with the numeric string the same as for positive numbers.
The final section is for text values, and all that this needs is a color (Blue) again within square brackets
This is the result of applying this format string:
You can go further with conditions within the format string. Suppose that you wanted to show every positive number above 10,000 as green, and every other number as red you could use this format string:
Range("A1:A7").NumberFormat = "[>=10000][Green]#,##0.00;[<10000][Red]#,##0.00"
This format string includes conditions for >=10000 set in square brackets so that green will only be used where the number is greater than or equal to 10000
This is the result:
Using Fractions in Formatting Strings
Fractions are not often used in spreadsheets, since they normally equate to decimals which everyone is familiar with.
However, sometimes they do serve a purpose. This example will display dollars and cents:
Range("A1:A7").NumberFormat = "#,##0 "" dollars and "" 00/100 "" cents """
This is the result that will be produced:
Remember that in spite of the numbers being displayed as text, they are still there in the background as numbers and all the Excel formulas can still be used on them.
Date and Time Formats
Dates are actually numbers and you can use formats on them in the same way as for numbers. If you format a date as a numeric number, you will see a large number to the left of the decimal point and a number of decimal places. The number to the left of the decimal point shows the number of days starting at 01-Jan-1900, and the decimal places show the time based on 24hrs
MsgBox Format(Now(), "dd-mmm-yyyy")
This will format the current date to show ’08-Jul-2020’. Using ‘mmm’ for the month displays the first three characters of the month name. If you want the full month name then you use ‘mmmm’
You can include times in your format string:
MsgBox Format(Now(), "dd-mmm-yyyy hh:mm AM/PM")
This will display ’08-Jul-2020 01:25 PM’
‘hh:mm’ represents hours and minutes and AM/PM uses a 12-hour clock as opposed to a 24-hour clock.
You can incorporate text characters into your format string:
MsgBox Format(Now(), "dd-mmm-yyyy hh:mm AM/PM"" today""")
This will display ’08-Jul-2020 01:25 PM today’
You can also use literal characters using a backslash in front in the same way as for numeric format strings.
VBA Programming | Code Generator does work for you!
Predefined Formats
Excel has a number of built-in formats for both numbers and dates that you can use in your code. These mainly reflect what is available on the number formatting front end, although some of them go beyond what is normally available on the pop-up window. Also, you do not have the flexibility over number of decimal places, or whether thousands separators are used.
General Number
This format will display the number exactly as it is
MsgBox Format(1234567.89, "General Number")
The result will be 1234567.89
Currency
MsgBox Format(1234567.894, "Currency")
This format will add a currency symbol in front of the number e.g. $, £ depending on your locale, but it will also format the number to 2 decimal places and will separate the thousands with commas.
The result will be $1,234,567.89
Fixed
MsgBox Format(1234567.894, "Fixed")
This format displays at least one digit to the left but only two digits to the right of the decimal point.
The result will be 1234567.89
Standard
MsgBox Format(1234567.894, "Standard")
This displays the number with the thousand separators, but only to two decimal places.
The result will be 1,234,567.89
AutoMacro | Ultimate VBA Add-in | Click for Free Trial!
Percent
MsgBox Format(1234567.894, "Percent")
The number is multiplied by 100 and a percentage symbol (%) is added at the end of the number. The format displays to 2 decimal places
The result will be 123456789.40%
Scientific
MsgBox Format(1234567.894, "Scientific")
This converts the number to Exponential format
The result will be 1.23E+06
Yes/No
MsgBox Format(1234567.894, "Yes/No")
This displays ‘No’ if the number is zero, otherwise displays ‘Yes’
The result will be ‘Yes’
True/False
MsgBox Format(1234567.894, "True/False")
This displays ‘False’ if the number is zero, otherwise displays ‘True’
The result will be ‘True’
AutoMacro | Ultimate VBA Add-in | Click for Free Trial!
On/Off
MsgBox Format(1234567.894, "On/Off")
This displays ‘Off’ if the number is zero, otherwise displays ‘On’
The result will be ‘On’
General Date
MsgBox Format(Now(), "General Date")
This will display the date as date and time using AM/PM notation. How the date is displayed depends on your settings in the Windows Control Panel (Clock and Region | Region). It may be displayed as ‘mm/dd/yyyy’ or ‘dd/mm/yyyy’
The result will be ‘7/7/2020 3:48:25 PM’
Long Date
MsgBox Format(Now(), "Long Date")
This will display a long date as defined in the Windows Control Panel (Clock and Region | Region). Note that it does not include the time.
The result will be ‘Tuesday, July 7, 2020’
Medium Date
MsgBox Format(Now(), "Medium Date")
This displays a date as defined in the short date settings as defined by locale in the Windows Control Panel.
The result will be ’07-Jul-20’
AutoMacro | Ultimate VBA Add-in | Click for Free Trial!
Short Date
MsgBox Format(Now(), "Short Date")
Displays a short date as defined in the Windows Control Panel (Clock and Region | Region). How the date is displayed depends on your locale. It may be displayed as ‘mm/dd/yyyy’ or ‘dd/mm/yyyy’
The result will be ‘7/7/2020’
Long Time
MsgBox Format(Now(), "Long Time")
Displays a long time as defined in Windows Control Panel (Clock and Region | Region).
The result will be ‘4:11:39 PM’
Medium Time
MsgBox Format(Now(), "Medium Time")
Displays a medium time as defined by your locale in the Windows Control Panel. This is usually set as 12-hour format using hours, minutes, and seconds and the AM/PM format.
The result will be ’04:15 PM’
Short Time
MsgBox Format(Now(), "Short Time")
Displays a medium time as defined in Windows Control Panel (Clock and Region | Region). This is usually set as 24-hour format with hours and minutes
The result will be ’16:18’
AutoMacro | Ultimate VBA Add-in | Click for Free Trial!
Dangers of Using Excel’s Pre-Defined Formats in Dates and Times
The use of the pre-defined formats for dates and times in Excel VBA is very dependent on the settings in the Windows Control Panel and also what the locale is set to
Users can easily alter these settings, and this will have an effect on how your dates and times are displayed in Excel
For example, if you develop an Excel application which uses pre-defined formats within your VBA code, these may change completely if a user is in a different country or using a different locale to you. You may find that column widths do not fit the date definition, or on a user form the Active X control such as a combo box (drop down) control is too narrow for the dates and times to be displayed properly.
You need to consider where the audience is geographically when you develop your Excel application
User-Defined Formats for Numbers
There are a number of different parameters that you can use when defining your format string:
Character | Description |
Null String | No formatting |
0 | Digit placeholder. Displays a digit or a zero. If there is a digit for that position then it displays the digit otherwise it displays 0. If there are fewer digits than zeros, then you will get leading or trailing zeros. If there are more digits after the decimal point than there are zeros, then the number is rounded to the number of decimal places shown by the zeros. If there are more digits before the decimal point than zeros these will be displayed normally. |
# | Digit placeholder. This displays a digit or nothing. It works the same as the zero placeholder above, except that leading and trailing zeros are not displayed. For example 0.75 would be displayed using zero placeholders, but this would be .75 using # placeholders. |
. Decimal point. | Only one permitted per format string. This character depends on the settings in the Windows Control Panel. |
% | Percentage placeholder. Multiplies number by 100 and places % character where it appears in the format string |
, (comma) | Thousand separator. This is used if 0 or # placeholders are used and the format string contains a comma. One comma to the left of the decimal point indicates round to the nearest thousand. E.g. ##0, Two adjacent commas to the left of the thousand separator indicate rounding to the nearest million. E.g. ##0,, |
E- E+ | Scientific format. This displays the number exponentially. |
: (colon) | Time separator – used when formatting a time to split hours, minutes and seconds. |
/ | Date separator – this is used when specifying a format for a date |
– + £ $ ( ) | Displays a literal character. To display a character other than listed here, precede it with a backslash () |
User-Defined Formats for Dates and Times
These characters can all be used in you format string when formatting dates and times:
Character | Meaning |
c | Displays the date as ddddd and the time as ttttt |
d | Display the day as a number without leading zero |
dd | Display the day as a number with leading zero |
ddd | Display the day as an abbreviation (Sun – Sat) |
dddd | Display the full name of the day (Sunday – Saturday) |
ddddd | Display a date serial number as a complete date according to Short Date in the International settings of the windows Control Panel |
dddddd | Displays a date serial number as a complete date according to Long Date in the International settings of the Windows Control Panel. |
w | Displays the day of the week as a number (1 = Sunday) |
ww | Displays the week of the year as a number (1-53) |
m | Displays the month as a number without leading zero |
mm | Displays the month as a number with leading zeros |
mmm | Displays month as an abbreviation (Jan-Dec) |
mmmm | Displays the full name of the month (January – December) |
q | Displays the quarter of the year as a number (1-4) |
y | Displays the day of the year as a number (1-366) |
yy | Displays the year as a two-digit number |
yyyy | Displays the year as four-digit number |
h | Displays the hour as a number without leading zero |
hh | Displays the hour as a number with leading zero |
n | Displays the minute as a number without leading zero |
nn | Displays the minute as a number with leading zero |
s | Displays the second as a number without leading zero |
ss | Displays the second as a number with leading zero |
ttttt | Display a time serial number as a complete time. |
AM/PM | Use a 12-hour clock and display AM or PM to indicate before or after noon. |
am/pm | Use a 12-hour clock and use am or pm to indicate before or after noon |
A/P | Use a 12-hour clock and use A or P to indicate before or after noon |
a/p | Use a 12-hour clock and use a or p to indicate before or after noon |
Преобразование чисел, дат и строк в настраиваемый текстовый формат из кода VBA Excel с помощью функции Format. Синтаксис, параметры, символы, примеры.
Format – это функция, которая преобразует число, дату или строку в текст, отформатированный в соответствии с именованным выражением формата или инструкциями, составленными из специальных символов.
Синтаксис и параметры
Format(Expression, [FormatExpression], [FirstDayOfWeek], [FirstWeekOfYear])
- Expression – любое допустимое выражение (переменная), возвращающее числовое значение или строку (обязательный параметр).
- FormatExpression – выражение формата, именованное или содержащее инструкции из специальных символов (необязательный параметр).
- FirstDayOfWeek – константа, задающая первый день недели (необязательный параметр).
- FirstWeekOfYear – константа, задающая первую неделю года (необязательный параметр).
Именованные выражения форматов
Именные форматы даты и времени
Имя формата | Описание |
---|---|
General Date | Стандартное отображение даты и времени в соответствии с параметрами системы. |
Long Date | Длинный формат даты. |
Medium Date | Средний формат даты. |
Short Date | Краткий формат даты. |
Long Time | Длинный формат времени. |
Medium Time | Средний формат времени. |
Short Time | Краткий формат времени. |
Проверьте отображение даты и времени с использованием именованных форматов на вашем компьютере при помощи следующего кода VBA Excel:
Sub FormatDateTime() MsgBox «General Date: « & Format(Now, «General Date») & vbNewLine _ & vbNewLine & «Long Date: « & Format(Now, «Long Date») & vbNewLine _ & vbNewLine & «Medium Date: « & Format(Now, «Medium Date») & vbNewLine _ & vbNewLine & «Short Date: « & Format(Now, «Short Date») & vbNewLine _ & vbNewLine & «Long Time: « & Format(Now, «Long Time») & vbNewLine _ & vbNewLine & «Medium Time: « & Format(Now, «Medium Time») & vbNewLine _ & vbNewLine & «Short Time: « & Format(Now, «Short Time») End Sub |
Скорее всего, результат будет таким:
Именованные форматы чисел
Имя формата | Описание |
---|---|
General Number | Стандартное отображение числа без знака разделителя групп разрядов. |
Currency | Денежный формат. |
Fixed | Отображение числа без знака разделителя групп разрядов с двумя цифрами после разделителя целой и дробной части. |
Standard | Отображение числа со знаком разделителя групп разрядов и с двумя цифрами после разделителя целой и дробной части. |
Percent | Процентный формат: отображение числа, умноженного на 100, со знаком процента (%), добавленного справа. |
Scientific | Отображение числа в экспоненциальном виде. |
Yes/No | Возвращается «Нет», если число равно 0, иначе отображается «Да». |
True/False | Возвращается «Ложь», если число равно 0, иначе отображается «Истина». |
On/Off | Возвращается «Выкл», если число равно 0, иначе отображается «Вкл». |
Проверяем работу именованных форматов на числах 2641387.7381962 и 0 с помощью кода VBA Excel:
Sub FormatNumber() Dim n As Double n = 2641387.7381962 ‘n = 0 MsgBox «Форматируемое число = « & n & vbNewLine _ & vbNewLine & «General Number: « & Format(n, «General Number») & vbNewLine _ & vbNewLine & «Currency: « & Format(n, «Currency») & vbNewLine _ & vbNewLine & «Fixed: « & Format(n, «Fixed») & vbNewLine _ & vbNewLine & «Standard: « & Format(n, «Standard») & vbNewLine _ & vbNewLine & «Percent: « & Format(n, «Percent») & vbNewLine _ & vbNewLine & «Scientific: « & Format(n, «Scientific») & vbNewLine _ & vbNewLine & «Yes/No: « & Format(n, «Yes/No») & vbNewLine _ & vbNewLine & «True/False: « & Format(n, «True/False») & vbNewLine _ & vbNewLine & «On/Off: « & Format(n, «On/Off») End Sub |
Получаем следующий результат:
Вместо вопросительного знака в отображении числа в формате Currency, по идее, должен быть знак валюты (₽ или руб.).
Специальные символы для выражений форматов
Символы для форматов даты и времени
Символ | Описание |
---|---|
Точка (.) | Разделитель компонентов даты (день, месяц, год). Используется при отображении месяца в виде числа. |
Пробел | Разделитель компонентов даты (день, месяц, год). Используется при отображении месяца прописью. |
Двоеточие (:) | Разделитель компонентов времени (часы, минуты, секунды). |
d | День в виде числа без нуля в начале (1–31). |
dd | День в виде числа с нулем в начале (01–31). |
m | Месяц в виде числа без нуля в начале (1–12). Если (m) следует после (h) или (hh), отображаются минуты (0–59). |
mm | Месяц в виде числа с нулем в начале (01–12). Если (mm) следует после (h) или (hh), отображаются минуты (00–59). |
mmm | Месяц прописью в сокращенном виде (янв–дек). |
mmmm | Полное название месяца (январь–декабрь). |
y | День года в виде числа (1–366). |
yy | Год в виде 2-значного числа (00–99). |
yyyy | Год в виде 4-значного числа (1900–9999). |
h | Часы в виде числа без нуля в начале (0–23). |
hh | Часы в виде числа с нулем в начале (00–23). |
n (m) | Минуты в виде числа без нуля в начале (0–59). |
nn (mm) | Минуты в виде числа с нулем в начале (00–59). |
s | Секунды в виде числа без нуля в начале (0–59). |
ss | Секунды в виде числа с нулем в начале (00–59). |
В этой таблице перечислены далеко не все символы для выражений форматов даты и времени. Вы можете ознакомиться со всеми символами, в том числе и для форматирования чисел, на сайте разработчика.
Примеры отображения даты с помощью разных по количеству наборов символа d:
Sub DataIsD() MsgBox «d: « & Format(Now, «d») & vbNewLine _ & vbNewLine & «dd: « & Format(Now, «dd») & vbNewLine _ & vbNewLine & «ddd: « & Format(Now, «ddd») & vbNewLine _ & vbNewLine & «dddd: « & Format(Now, «dddd») & vbNewLine _ & vbNewLine & «ddddd: « & Format(Now, «ddddd») & vbNewLine _ & vbNewLine & «dddddd: « & Format(Now, «dddddd») End Sub |
Символы для числовых форматов
Символ | Описание |
---|---|
Точка (.) | Десятичный разделитель. |
Запятая (,) | Разделитель групп разрядов. В отображаемых числах заполняется пробелом. |
(0) | Заполнитель, который отображает цифру или ноль. Используется, когда нужны ведущие нули или нули в конце числа. |
(#) | Заполнитель, который отображает цифру или ничего не отображает. Используется, когда не нужны ведущие нули или нули в конце числа. |
(%) | Заполнитель процента. Выражение умножается на 100, а знак процента (%) вставляется на той позиции, где он указан в строке формата. |
(E- E+ e- e+) | Экспоненциальный формат. |
Примеры использования символов в выражениях числовых форматов VBA Excel:
Sub FormatNumber2() Dim n As Double n = 2641387.7381962 ‘n = 0.2397842 MsgBox «Форматируемое число = « & n & vbNewLine _ & vbNewLine & «0.##: « & Format(n, «0.##») & vbNewLine _ & vbNewLine & «000.###: « & Format(n, «000.###») & vbNewLine _ & vbNewLine & «#,###.###: « & Format(n, «#,###.###») & vbNewLine _ & vbNewLine & «0 %: « & Format(n, «0 %») & vbNewLine _ & vbNewLine & «0.### E-: « & Format(n, «0.### E-«) & vbNewLine _ & vbNewLine & «0.### E+: « & Format(n, «0.### E+») End Sub |
Символы для текстовых форматов
Символ | Описание |
---|---|
At-символ (@) | Заполнитель для символов, отображающий знак или пробел. |
Амперсанд (&) | Заполнитель для символов, отображающий знак или ничего (пустая строка). |
Меньше (<) | Принудительный перевод всех буквенных символов в нижний регистр. |
Больше (>) | Принудительный перевод всех буквенных символов в верхний регистр. |
Примеры использования символов в выражениях строковых форматов VBA Excel:
Sub FormatString() MsgBox «Номер телефона: « & Format(«1234567890», «+7 (@@@) @@@-@@-@@») & vbNewLine _ & vbNewLine & «Серия и номер паспорта: « & Format(«1234567890», «&& && &&&&») & vbNewLine _ & vbNewLine & «Нижний регистр: « & Format(«Нижний регистр», «<«) & vbNewLine _ & vbNewLine & «Верхний регистр: « & Format(«Верхний регистр», «>») End Sub |
Форматы для различных значений одного выражения
Различные форматы для разных числовых значений
В выражении формата для чисел предусмотрено от одного до четырех разделов, отделяемых друг от друга точкой с запятой. Отображаемая строка зависит от значения, возвращенного параметром Expression функции Format.
Количество разделов | Результат форматирования |
---|---|
Один раздел | Выражение формата применяется ко всем значениям. |
Два раздела | Первый раздел применяется к положительным значениям и нулям, второй – к отрицательным значениям. |
Три раздела | Первый раздел применяется к положительным значениям, второй – к отрицательным значениям, третий – к нулям. |
Четыре раздела | Первый раздел применяется к положительным значениям, второй – к отрицательным значениям, третий – к нулям, четвертый – к значениям Null. |
Пример использования четырех разделов в выражении формата числовых значений:
Sub FormatDifferentValues() MsgBox «Число 1234,5678: « & _ Format(1234.5678, «#,##0.00 руб.;Отрицательное число;Ноль рублей;Значение Null») _ & vbNewLine & vbNewLine & «Число -25: « & _ Format(—25, «#,##0.00 руб.;Отрицательное число;Ноль рублей;Значение Null») _ & vbNewLine & vbNewLine & «Число 0: « & _ Format(0, «#,##0.00 руб.;Отрицательное число;Ноль рублей;Значение Null») _ & vbNewLine & vbNewLine & «Null: « & _ Format(Null, «#,##0.00 руб.;Отрицательное число;Ноль рублей;Значение Null») End Sub |
Различные форматы для разных строковых значений
В выражении формата для строк предусмотрено до двух разделов, отделяемых друг от друга точкой с запятой. Отображаемая строка зависит от текста, возвращенного параметром Expression функции Format.
Количество разделов | Результат форматирования |
---|---|
Один раздел | Выражение формата применяется ко всем строковым данным. |
Два раздела | Первый раздел применяется к строковым данным, второй – к значениям Null и пустым строкам («»). |
Пример использования двух разделов в выражении формата строк:
Sub FormatString2() MsgBox «Строка «Белка»: « & _ Format(«Белка», «@;Пустая строка или Null») _ & vbNewLine & vbNewLine & «Пустая строка: « & _ Format(«», «@;Пустая строка или Null») _ & vbNewLine & vbNewLine & «Строка «Null»: « & _ Format(«Null», «@;Пустая строка или Null») _ & vbNewLine & vbNewLine & «Значение Null: « & _ Format(Null, «@;Пустая строка или Null») End Sub |
Format function in VBA is a function one may use to format the given values in the desired format. This function has two mandatory arguments: the input, which takes the form of a string, and the second argument, which is the type of format we want to use. For example, if we use Format (.99,” Percent”) this will give us the result as 99%.
Format Number in VBA Excel
VBA stands way ahead of regular excel functionsExcel functions help the users to save time and maintain extensive worksheets. There are 100+ excel functions categorized as financial, logical, text, date and time, Lookup & Reference, Math, Statistical and Information functions.read more. It happens because VBA has many built-in functions, just like we have more than 500 operations in the worksheet. For example, one such formula in VBA is “Format Number.”
Yes, you heard it right. We have a function called “FormatNumber” in VBA. This article will take a complete tour of this function exclusively.
Table of contents
- Format Number in VBA Excel
- How to Format Numbers with VBA NumberFormat?
- Examples of Excel VBA FormatNumber Function
- Example #1 – Add Decimal Points in Front of the Number
- Example #2 – Group Number i.e., Thousand Separator
- Example #3 – Enclose Parenthesis for Negative Numbers
- Recommended Articles
How to Format Numbers with VBA NumberFormat?
As the function name says, it will format the given number according to the user’s formatting instructions.
Number formatting is nothing but adding decimal points, enclosing negative numbers in parenthesis, showing leading zeroesLeading zeros are zeros that are added to figures without altering their mathematical values. This is done to keep a specific format in a sheet or to prevent errors. We may add Leading Zeros in Excel by utilizing the Right, TEXT, and Concatenate Functions.read more for decimal values, etc. Using the VBA FormatNumber function, we can apply the formatting style to the numbers we work with. Below is the syntax of the function.
- Expression: This is nothing but the number we need to format.
- Num Digits After Decimal: How many digits do you want for decimals positioned on the right side of the number?
- Include Leading Digit: Leading digit is nothing but digits before the number starts. It is applicable for values less than 1 but greater than -1.
- If you want to show zero before the decimal value, you can pass the argument as TRUE or -1, and the result will be “0.55.“
- If you don’t want to show zero before the decimal value, you can pass the argument as FALSE or 0, and the result will be “.55.”
- The value will default be -2, i.e., regional computer settings.
- Use Parents for Negative Numbers: If you wish to show the negative numbers in parenthesis, you can pass the argument as TRUE or -1, and the result will be “(255).”
- If you wish to show the negative numbers without parentheses, you can pass the argument as FALSE or 0, and the result will be “-255.”
- Group Digits: Whether you want to add a thousand separators or not. If yes, TRUE or -1 is the argument. If not, FALSE or 0 is the argument. By default, the value is -2, i.e., equal to regional computer settings.
Examples of Excel VBA FormatNumber Function
We will see the practical examples of the Excel VBA FormatThe format function in VBA is used to format the given values into the format that is desired. It can be used to format dates, numbers, and trigonometrical values, among other things.read more Number function. We will perform every argument separately.
For this purpose, create the macro name and declare one of the variables as a string. We need to report the variable as a string because the result given by the VBA function FormatNumber is a string only.
You can download this VBA Format Number Function Template here – VBA Format Number Function Template
Code:
Sub Format_Number_Example1() Dim MyNum As String End Sub
Example #1 – Add Decimal Points in Front of the Number
Step #1 – Assume we have been working with the number 25000, and we need to format it and add decimal points to the right of the number. Assign a value to our variable.
Code:
Sub Format_Number_Example1() Dim MyNum As String MyNum = FormatNumber( End Sub
Step #2 – First up is an expression, i.e., the number we need to format, so our number is 25000.
Code:
Sub Format_Number_Example1() Dim MyNum As String MyNum = FormatNumber(25000, End Sub
Step #3 – Next is how many digits we need to add, i.e., 2 numbers.
Code:
Sub Format_Number_Example1() Dim MyNum As String MyNum = FormatNumber(25000, 2) End Sub
Step #4 – Show the variable’s value in the VBA message boxVBA MsgBox function is an output function which displays the generalized message provided by the developer. This statement has no arguments and the personalized messages in this function are written under the double quotes while for the values the variable reference is provided.read more.
Code:
Sub Format_Number_Example1() Dim MyNum As String MyNum = FormatNumber(25000, 2) MsgBox MyNum End Sub
Step #5 – The result of this macro is like this.
We can see two decimals to the right of the number.
Example #2 – Group Number i.e., Thousand Separator
For the same number, we can add or delete a thousand separators. If we want to show a thousand separators, we must select vbTrue for the last argument.
Code:
Sub Format_Number_Example1() Dim MyNum As String MyNum = FormatNumber(25000, 2, , , vbTrue) MsgBox MyNum End Sub
It will throw the result like this.
Now, if we select vbFalse, we will not get a thousand separators.
Code:
Sub Format_Number_Example1() Dim MyNum As String MyNum = FormatNumber(25000, 2, , , vbFalse) MsgBox MyNum End Sub
The result of this code is like this.
If we select vbUseDefault, we get the result per the system setting. Below is the result of this.
So, my system setting has a thousand separators by default.
Example #3 – Enclose Parenthesis for Negative Numbers
We can show the negative number in parenthesis if we have a harmful number. We need to select vbTrue under “Use Parents for Negative Numbers.”
Code:
Sub Format_Number_Example1() Dim MyNum As String MyNum = FormatNumber(-25000, 2, , vbTrue) MsgBox MyNum End Sub
Now, the result is like this.
If we select vbFalse, we will get a negative number with a minus sign.
Code:
Sub Format_Number_Example1() Dim MyNum As String MyNum = FormatNumber(-25000, 2, , vbFalse) MsgBox MyNum End Sub
Now, the result is like this.
Recommended Articles
This article is a guide to VBA Format Number Function. Here, we learn how to format numbers using VBA Format Number in Excel, some practical examples, and a downloadable Excel template. Below are some useful Excel articles related to VBA: –
- VBA Set
- Use VLookup in VBA
- Excel Negative Numbers
- VBA ISERROR
Excel VBA Number Format
VBA Number Format though looks simple but it is very important to master them. In VBA, we have several ways to format numbers, we have the Number Format Function.
When it comes to range object, we use the property Range.NumberFormat to format numbers in the range. In today’s article, we will see how to use number format in range object to apply formatting style to our numbers.
What does Number Format Function do in VBA?
Just to remind you, excel stores all numerical values as serial numbers, be it date or time this will also be stored as serial numbers. According to the format given by the user to the serial number, it will display the result.
For example assume you have the number 43542 in cell A2.
Now I will apply the date format of “dd-mmm-yyyy”.
And it will display the result as 18-Mar-2019.
Similarly in VBA as well we will perform the same job by using number format property.
How to Use Number Format Function in VBA?
Let’s understand how to use Number Format Function in VBA with some examples.
You can download this VBA Number Format Excel Template here – VBA Number Format Excel Template
Example #1
Ok, we will see how to format the same cell value using VBA code. I will remove the date format I have applied to the serial number 43542 in cell A2.
Now go to VBA editor and create a macro name.
Code:
Sub NumberFormat_Example1() End Sub
Now we need to tell which cell actually we want to format, in this case, we need to format the cell A2. So write the code as “Range (“A2”)”
Code:
Sub NumberFormat_Example1() Range ("A2") End Sub
After selecting the cell to select the property called “NumberFormat” by putting dot (.)
After selecting the property put an equal sign.
Now apply the format we wish to apply in this case, format is date format i.e. “dd-mmm-yyyy” format.
Code:
Sub NumberFormat_Example1() Range("A2").NumberFormat = "dd-mmm-yyyy" End Sub
Now run this code, it will display the result exactly the same as the worksheet number formatting.
Example #2
Format Numbers using Built-in Formats
Assume you have few numbers from cell A1 to A5.
We will try out different built-in number formats. Some of the number formats are “Standard”, General”, “Currency”, “Accounting”.
To apply the formatting we need to select the range of cells first, here the range of cells is from A1 to A5 and then select the number format property.
Apply the number format as “General”.
Code:
Sub NumberFormat_Example2() Range("A1:A5").NumberFormat = "General" End Sub
Example #3
As “General” doesn’t have any impact on default numbers we don’t see changes. So apply the currency format and code for currency format is “#,##0.00”.
Code:
Sub NumberFormat_Example3() Range("A1:A5").NumberFormat = "#,##0.0" End Sub
This will apply the currency format like the below.
Example #4
If you wish to have currency symbol you can provide the currency symbol just before the code.
Code:
Sub NumberFormat_Example4() Range("A1:A5").NumberFormat = "$#,##0.0" End Sub
This code will add a currency symbol to the numbers as part of the formatting.
Example #5
Format Percentage Values
Now we will see how to format percentage values. For this example, I have created some of the percentage values from cell A1 to A5.
Now select the range and select Number Format property.
Apply the formatting code as “0.00%”.
Code:
Sub NumberFormat_Example5() Range("A1:A5").NumberFormat = "0.00%" End Sub
Run this code using F5 key or manually then it will convert all the values to the percentage.
Now, look at the cells a2 & a5 we have negative values. As part of the formatting, we can show the negative values in red color as well. To show all the negative values formatting code is “0.00%;[Red]-0.00%”
Code:
Sub NumberFormat_Example5() Range("A1:A5").NumberFormat = "0.00%;[red]-0.00%" End Sub
Run this code using F5 key or manually and we will have all the negative percentage values in red color.
Example #6
Format Positive Numbers and Negative Numbers
As we can format numbers we can play around with them as well. Assume few numbers from range A1 to A5 which includes negative numbers as well.
As we have shown in the percentage here also we can show all the negative numbers in red color. To show negative numbers in red color code is “#,##.00;[red]-#,##.00”
Code:
Sub NumberFormat_Example6() Range("A1:A5").NumberFormat = "#,##.00;[red]-#,##.00" End Sub
This will format the numbers like this.
We can also show negative numbers in red as well as in brackets. To do this below is the formatting code.
Code:
Sub NumberFormat_Example6() Range("A1:A5").NumberFormat = "#,##.00;[red](-#,##.00)" End Sub
Run this code using F5 keys or manually and this will format the numbers like this.
Example #7
Text with Number Formatting
The beauty of number formatting is we can also add text values to it. I have a list of items that measure their weight in “Kg’s”.
The problem here is Carrot’s weight says 30, by looking at this weight reader cannot understand whether it is 30 grams or 30 kgs. So we will format this by using VBA code.
Code:
Sub NumberFormat_Example7() Range("B2:B6").NumberFormat = "0#"" Kg""" End Sub
Run this code using F5 key or manually and this will add the word “Kg” in front of all the number from B2 to B6.
Recommended Articles
This has been a guide to VBA Number Format Function. Here we discussed how to use Excel VBA Number Format Function along with some practical examples and downloadable excel template. You can also go through our other suggested articles –
- FIND Function in Excel with Examples
- What is VBA Function in Excel?
- Guide to VBA Range Object
- How to use VBA VLOOKUP Function?
- How to Use Negative Numbers in Excel?
Custom Number Formats, Date & Time Formats in Excel & VBA; NumberFormat property
—————————————————————————
Contents:
Custom Number Formats in Excel / VBA
Excel Home Tab, Format Cells dialog box
VBA, NumberFormat property
Number Codes
Text Codes
Specify Font Color
Four Sections of Code
Specify Conditions
Custom Date & Time Formats in Excel / VBA
Display Date Format in Days, Months and Years
Display Time Format as Hours, Minutes and Seconds
Examples of Date & Time Formats
—————————————————————————
Custom Number Formats in Excel / VBA
In excel, default format for a cell is «General». When you first enter a number in a cell, Excel tries to guess an appropriate format, viz. if you type $5 in a cell, it will format the cell to Currency; if you type 5%, it will format to a percentage. However, many times you will need to select or add an appropriate format, especially if you want a customized display. It is important to note that formatting a cell only effects its display and does not change or effect its actual or true value (which is used by Excel for calculations) ie. if you select a formatted cell, the formula bar will display the value which was typed before it was formatted (Note: in a percentage format, if you type 0.75 in a cell, it is displayed as 75% after applying the format). In excel, by default, text is left aligned and non-text (viz. numbers, percentage, date/time, …) are right aligned, unless you specifically change this. We show how to create Custom Number Formats: (i) in Excel Spreadsheet, in the Format Cells dialog box; and (ii) in VBA, using the NumberFormat property.
Excel Home Tab, Format Cells dialog box
On the Home Tab, Format menu, click Format Cells (or Cells) and select the Number tab; OR On the Home tab, click the Dialog Box Launcher Button image next to Number. After this, in the Category list, select Custom, and all built-in and custom number formats will be displayed. In the «Type» box, type the number format code.
The built-in number formats cannot be changed or deleted. You can type in to add a custom number format, which will get added at the bottom of the list. You can delete a custom number format by clicking on the Delete button. If you edit a custom number format, the original is retained and the new format also gets added to the list. It is therefore advisable to delete the custom number formats which are not required.
Custom number formats are specific to the workbook they are created in and will be saved and available only in that specific workbook. You can save the original workbook and use the custom number formats in additional workbooks.
Example: Enter Format Code in Excel (Home Tab) Format Cells dialog box:
Select the cells / range in your worksheet in which to apply the format, and then in the «Type» box type the number format code. Note that the number format code is not required to be enclosed in double quotation marks like in VBA. Type below format code:
_(#,###.00_);[Red](#,###.00);0.00
VBA, NumberFormat property
Use the NumberFormat Property to set or return the number format for the specified object, in VBA. You can apply the NumberFormat property to set the format code of a Range object, CellFormat object, PivotField object (only for a data field), DataLabel object, DataLabels Object, and so on. Syntax: expression.NumberFormat. It is necessary to specify an expression, which returns an object (say, Range object) for which you want to set or return the format code. If the number format for all cells in the specified range is not the same, this property will return Null.
NumberFormat property sets the number format in VBA. Use this property to format numbers and how they appear in cells. You can define a number format by using the same format code strings as Microsoft Excel (in the Format Cells dialog box). The NumberFormat property uses different code strings than the Format function.
Examples of VBA Code, with NumberFormat property:
ActiveSheet.Columns(«D»).NumberFormat = «#,###.00;[Red](#,###.00);0.00»
ActiveSheet.Rows(2).NumberFormat = «hh:mm:ss.00»
ActiveSheet.Range(«A5»).NumberFormat = «General»
The three codes set the number format in the Active Worksheet, for Column D, Row 2 and Cell A5 respectively. Note that the number format code is required to be enclosed in double quotation marks unlike when you enter in Excel,Home Tab, Format Cells dialog box.
————————————————————————————————————————
Number Codes
Format Character | Description | Format Code | Number | Formatted Display |
0 (zero) | Digit placeholder. If the number has lesser number of digits than zeros in the format code, the insignificant zeros are displayed. This means that the minimum number of digits are determined by the position of zero at the extreme left before decimal and position of zero at extreme right after decimal, in the format code. | |||
If the number has more digits than zeros to the left of the decimal point in the format code, the extra digits are displayed. | ||||
The number of zeros to the right of the decimal point in the format code, determine the round off digits. The «00» format code rounds off to the nearest digit preceding the decimal point. | ||||
0.00 | 5.6 | 5.60 | ||
00.00 | 5.6 | 05.60 | ||
0.0 | 5.6 | 5.6 | ||
0 | 0.6 | 1 | ||
00.00 | 456.789 | 456.79 | ||
00 | 45.445 | 45 | ||
# (number character) | Digit placeholder. This follows the same rules as 0 (zero), except that, if the number has lesser number of digits than «#» characters in the format code, the insignificant zeros are NOT displayed, even though it may be the only digit. | |||
If the number has more digits than # characters to the left of the decimal point in the format code, the extra digits are displayed. | ||||
The number of # to the right of the decimal point in the format code, determine the round off digits. The «##» format code rounds off to the nearest digit preceding the decimal point. | ||||
###.## | 456.6 | 456.6 | ||
# | 456.68 | 457 | ||
Where x is a numerical digit => | (###) ### — #### | 123456xxxx | (123) 456 — xxxx | |
##.# | 456.689 | 456.7 | ||
## | 45.678 | 46 | ||
? (question mark) | Digit placeholder. This follows the same rules as 0 (zero), except that, the character «?» leaves (ie. adds) a space for insignificant zeros either side of the decimal, while character zero displays «0» for them. It is particulalry useful to align decimal points in a column — you can align numbers decimally by adding spaces on either side of a number as required . | |||
If the number has more digits than ? characters to the left of the decimal point in the format code, the extra digits are displayed. | ||||
The number of ? to the right of the decimal point in the format code, determine the round off digits. The «??» format code rounds off to the nearest digit preceding the decimal point. | ||||
???.?? | 45.64 | 45.64 | ||
???.?? | 5.6 | 5.6 | ||
000.00 | 45.64 | 045.64 | ||
000.00 | 5.6 | 005.60 | ||
??.? | 456.689 | 456.7 | ||
?? | 45.678 | 46 | ||
. (period) | Decimal point. The decimal point (ie. the «.» character) in the format code determines the decimal place. | |||
The number of Digit Placeholders to the right of the decimal point in the format code, determine the round off digits. The «00» or «##» or «??» format codes round off to the nearest digit preceding the decimal point. | ||||
00.000 | 456.123456 | 456.123 | ||
00.00 | 456.789567 | 456.79 | ||
##.# | 456.789567 | 456.8 | ||
##.# | 0.65 | .7 | ||
, (comma) | Thousand separator and number scaling | |||
Thousand separator: In the format code, placing comma between two digit placeholders and to the left of decimal, will act as a thousand separator. | ||||
Number Scaling: If comma is placed to the immediate left of the decimal point (in the format code), the number is divided by 1,000, n number of times wherein n is the number of characters «,». The format string «0,,» will scale down the number 100 million to 100 (divides 100 million by 1,000 * 1,000); and the format code «0,,,» will divide the number by 1,000 * 1,000 * 1,000. Note that this number scaling will not apply the thousand separator, which will have to be done separately after the number scaling. | ||||
# | 123456 | 123456 | ||
#,### | 123456 | 123,456 | ||
#,#00 | 123456 | 123,456 | ||
#,###.## | 4567.234 | 4,567.23 | ||
0, | 10000 | 10 | ||
#,##0,, | 1000000 | 1 | ||
#,###.#, | 12345.678 | 12.3 | ||
% (percent sign) | Percentage indicator. Numbers are displayed as a percentage of 100 with this. The percent sign in the format code multiplies the number by 100, before it is formatted. The symbol «%» is displayed at the same position at which it is inserted in the format code. | |||
#.0% | 0.00625 | .6% | ||
0.000% | 0.00625 | 0.625% | ||
#.##% | 0.00625 | .63% | ||
%# | 0.5625 | %56 | ||
/ (forward slash) | Fraction format. The forward slash displays number in a fraction format (ie. non-decimal format). The extent of accuracy of the fraction is determined by the number of digit placeholders on the right of the «/» character. | |||
#/# | 1.237 | 5/4 | ||
#/## | 1.237 | 47/38 | ||
#/### | 1.237 | 1023/827 |
Text Codes
Format Character | Description | Format Code | Number | Formatted Display |
E+ E- e+ e- | Scientific notation (exponential format). «E+» and «E-» followed by atleast one «0» character (in format code), displays the number in scientific notation, with the character «E» mentioned between the number and the exponent. The number of «0» characters determine the minimum number of exponent digits. «E+» indicates that the sign character (plus or minus) will always precede the exponent, whereas «E-» indicates that the sign character (minus) precedes only negative exponents. | |||
The E stands for exponent. To avoid writing extremely long numbers, use scientific notation (SN), ie. a numeric value containing the letter E followed by a number. To convert a SN number say 5.0E+3 to the actual number, move the decimal position 3 positions to the right OR multiply the number to the left of E by 10 raised to the powerof 3 viz. the actual number is 5000. If the exponent is negative, like in 5.25E-3, move the decimal position 3 positions to the left OR multiply the number to the left of E by 10 raised to the power of -3 viz. the actual number is -0.00525. |
||||
0.00E+0 | 4560000 | 4.56E+6 | ||
#0.0E+00 | 4560000 | 4.6E+06 | ||
0.###E+0 | 123.456 | 1.235E+2 | ||
##E+0 | 0.0001234 | 1E-4 | ||
##E-0 | 123456 | 12E4 | ||
##E-0 | 0.0001234 | 1E-4 | ||
$ / + — ( ) space | Literal characters. These are displayed as literals (exactly as typed) as per their position in the format code. Use these to display currency, to differentiate positive and negative numbers and for a more user-friendly display. | |||
$ +#,###.00 | 1456.7 | $ +1,456.70 | ||
(backslash) | Backslash. Any character appearing after backslash () will display as a literal, even though it may be reserved as an operator (say, %). The number 0.75 with the format code #.00% will format to 75.00%, but with the format code #.00% it will format to .75%, ie. format code will not use % as operator but as a literal. To display several characters as literals enclose these in double quotation marks (» «) or in case of a single character, precede it with a backslash (). | |||
On typing any of the characters { } = < > : ! ^ & ‘ ~ backslash () is automatically inserted before the character and it gets displayed as a literal. Hence these characters, alongwith the literal characters mentioned above, are displayed exactly as typed without the use of quotation marks or backslash (refer Table 1). | ||||
#.00% | 0.75 | .75% | ||
#.00% | 0.75 | 75.00% | ||
_ (underscore) | Add spaces. An underscore followed by a character in the format code, creates a space which is equivalent to the width of that character. A usual format is an underscore followed by left or right paranthesis viz. _( _), which aligns the decimal points of positive numbers with negative numbers that are enclosed in paranthesis. | #,###.00;[Red](#,###.00);0.00 | 567 | 567.00 |
_(#,###.00_);[Red](#,###.00);0.00 |
567 | 567.00 | ||
_(#,###.00_);[Red](#,###.00);0.00 |
-567 | (567.00) | ||
* (asterik) | Repeat characters. An asterik followed by a character in the format code, will repeat that character to fill the column width. Only one asterik can be included in a section. Use asterik to fill in dashes after a number, to fill in lead spaces before a number (which will right align it) or lead zeros before a number. | |||
0.0*- | 1.23 | 1.2——— | ||
* 0.0 | 1.23 | 1.2 | ||
*00.0 | 1.23 | 00000 1.2 | ||
@ (at character) | Text placeholder. Insert the @ character in the text section (the last & fourth section), to display text which you type in a cell. If you want to always display a specified text in addition to the text you type in a cell, insert this ‘always display text’ within double quotation marks (» «) and insert the @ character in the text section viz. «Text»@. Text will not be displayed if the «@» character is not inserted in this section. | |||
Text Section Format, in both Excel Format Cells dialog box and VBA with NumberFormat property: => | «[Blue]#,###.00; [Red](0.0#); [Green]0.00; [Magenta]@» | Jack | Jack | |
Text Section Format, in Excel Format Cells dialog box: => |
[Blue]#,###.00;[Red] (0.0#);[Green] 0.00;[Magenta] «Hello «@ |
Jack | Hello Jack | |
£ € ¥ | Currency symbols. In VBA, use the Chr function to insert currency symbols though their ANSI / ASCII code. Note that $ can be entered as a literal character, as mentioned above. | |||
Enter Currency symbols, in VBA with NumberFormat property: => | Chr(163) & «0.00» | 123 | £123.00 | |
Enter Currency symbols, in VBA with NumberFormat property: => | Chr(128) & «0.0» | 123 | €1.2 | |
Enter Currency symbols, in VBA with NumberFormat property: => | «#,### » & Chr(165) | 123 | 1.234 ¥ | |
Enter Currency symbols, in both Excel Format Cells dialog box and VBA with NumberFormat property: «£0.00», «€0.0», «#,### ¥», «£#,###», … => | «£#,###» | 123 | £123 |
———————————————————————————————————————————————
———————————————————————————————————————————————
Specify Font Color
Format Character | Description | Format Code | Number | Formatted Display |
[Black] [White] [Red] [Green] [Blue] [Yellow] [Magenta] [Cyan] | Font color. Enter color name (viz. Red) or color index (viz. Color 3) in square brackets (in the format code) to determine font color. Enter color as the first item in the section. Supported colors are the first 8 colors in the palette: Black (Color 1), White (Color 2), Red (Color 3), Green (Color 4), Blue (Color 5), Yellow (Color 6), Magenta (Color 7), Cyan (Color . | |||
[Red]#0.0 | 456 | 456.0 | ||
[Color 5]#0.0 | 456 | 456.0 |
Four Sections of Code
Format Character | Description | Format Code | Number | Formatted Display |
; (semicolon) | Section separator. There can be upto four sections of code in a custom number format, wherein each section is separated by a semicolon. These sections determine the display of positive numers, negative numbers, zero value and text, in that order. If only one section is specified in the format code, it applies to all the four sections; if two sections are specified, the first applies to positive and zero values and the second section applies to negative numbers. If all four sections are specified, only then is the text affected by the fourth section. | |||
You can also skip a section and specify code for the following or preceding section, but then you must enter the ending semicolon for the skipped section. Skipping a section(s) will result in a blank display for that section. If all sections are skipped ie. only 3 semicolons are entered, will mean a blank display for all numbers & text. However, if the first 3 sections are skipped and the text section (fourth section) is entered with the @ character, will mean a text display for all numbers & text (ie. for all 4 sections). | ||||
[Blue]#,###.00;[Red](0.0#);[Green]0.00;[Magenta]@ | 1456.7 | 1,456.70 | ||
[Blue]#,###.00;[Red](0.0#);[Green]0.00;[Magenta]@ |
-1456.7 | (1456.7) | ||
[Blue]#,###.00;[Red](0.0#);[Green]0.00;[Magenta]@ |
0 | 0.00 | ||
[Blue]#,###.00;[Red](0.0#);[Green]0.00;[Magenta]@ |
hello | hello |
Specify Conditions
Format Character | Description | Format Code | Number | Formatted Display |
= < > <= >= <> | Specify Conditions. You have an option to specify conditions subject to which a number format is to be applied. The condition should be enclosed in square brackets and it consists of a comparison operator and a value. Comparison operators which can be used are: = < > <= >= <>. The first three sections in the number format are by default applied to positive, negative, and zero values. However you can specify upto two of your own conditions by using comparison operators. | |||
[Green][>=70]0.00;[Blue][>=40]0.0;[Red]0;[Magenta]@ | 75 | 75.00 | ||
[Green][>=70]0.00;[Blue][>=40]0.0;[Red]0;[Magenta]@ |
51.55 | 51.6 | ||
[Green][>=70]0.00;[Blue][>=40]0.0;[Red]0;[Magenta]@ |
25.62 | 26 | ||
[Green][>=70]0.00;[Blue][>=40]0.0;[Red]0;[Magenta]@ |
hello | hello |
Custom Date & Time Formats in Excel / VBA
Display Date Format in Days, Months and Years
Code | Description | Display |
d | Day is displayed as a number, as one digit or as two digit. | 1-31 |
dd | Day is displayed as a number, as two digit, with a leading zero where applicable. | 01-31 |
ddd | Day is abbreviated to three letters, viz. Sunday is displayed as Sun. | Sun-Sat |
dddd | Day is displayed in its full format, viz. Sunday is displayed as Sunday. | Sunday-Saturday |
m | Month is displayed as a number, as one digit or as two digit. | 1-12 |
mm | Month is displayed as a number, as two digit, with a leading zero where applicable. | 01-12 |
mmm | Month name is abbreviated to three letters, viz. January is displayed as Jan. | Jan-Dec |
mmmm | Month is displayed in its full name, viz. January is displayed as January. | January-December |
mmmmm | Month is displayed as a single letter, viz. January is displayed as J. | J-D |
yy | Year is displayed as a number in two digits, viz. last 2 digits of the year are displayed. | 00-99 |
yyyy | Year is displayed as a number in four digits, viz. all digits of the year are displayed. | 1900-9999 |
Display Time Format as Hours, Minutes and Seconds
Code | Description | Display |
h | Hour is displayed as a number, as one digit or as two digit. | 0-23 |
hh | Hour is displayed as a number, as two digit, with a leading zero where applicable. | 00-23 |
[h] or [hh] | Elapsed time in hours is displayed. Format code «[h]:mm:ss» displays elapsed time in hours, minutes & seconds. Ex. Code «[h]:mm:ss» will display as => | 37:18:32 |
m | Minute is displayed as a number, as one digit or as two digit. Note that the «m» code is also used for displaying month. To use this code as minute(s), it should appear immediately after the h or hh code or immediately before the s or ss code, such as «m:ss». | 0-59 |
mm | Minute is displayed as a number, as two digit, with a leading zero where applicable. Note that the «mm» code is also used for displaying month. To use this code as minute(s), it should appear immediately after the h or hh code or immediately before the s or ss code, such as «h:mm». | 00-59 |
[m] or [mm] | Elapsed time in minutes is displayed. Format code «[mm]:ss» displays elapsed time in minutes & seconds. Ex. Code «[mm]:ss» will display as => | 64:48 |
s | Second is displayed as a number, as one digit or as two digit. Fractions of a second can be displayed by a format like «h:m:s.00». | 0-59 |
ss | Second is displayed as a number, as two digit, with a leading zero where applicable. Fractions of a second can be displayed by a format like «h:m:ss.00». | 00-59 |
[s] or [ss] | Elapsed time in seconds is displayed. Format code «[ss].00» displays elapsed time in seconds and its fraction(s). Ex. Code «[ss].00» will display as => | 1036.80 |
AM/PM, am/pm, A/P, a/p | If these codes are included in the format, the hour is displayed using a 12-hour clock, else the hour is based on the 24-hour format. Display will include AM, am, A or a for a time before noon, and PM, pm, P or p for a time ‘from’ and ‘after’ noon. Ex. Code «hh:mm:ss AM/PM» will display as => | 01:27:50 AM |
Examples of Date & Time Formats
Format Code | Display |
mm/dd/yyyy | 01/02/2010 |
m/d/yy | 1/2/10 |
ddd, mmmm d, yyyy | Sat, January 2, 2010 |
m/dd/yyyy hh:mm:ss.00 AM/PM | 5/15/2011 12:59:02.40 PM |
h:mm:s | 1:17:2 |
hh:mm:ss | 01:17:02 |