Преобразование чисел, дат и строк в настраиваемый текстовый формат из кода 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 |
title | keywords | f1_keywords | ms.prod | ms.assetid | ms.date | ms.localizationpriority |
---|---|---|---|---|---|---|
Format function (Visual Basic for Applications) |
vblr6.chm1008925 |
vblr6.chm1008925 |
office |
67f60abf-0c77-49ec-924f-74ae6eb96ea8 |
08/14/2019 |
high |
Returns a Variant (String) containing an expression formatted according to instructions contained in a format expression.
[!includeAdd-ins note]
Syntax
Format(Expression, [ Format ], [ FirstDayOfWeek ], [ FirstWeekOfYear ])
The Format function syntax has these parts.
Part | Description |
---|---|
Expression | Required. Any valid expression. |
Format | Optional. A valid named or user-defined format expression. |
FirstDayOfWeek | Optional. A constant that specifies the first day of the week. |
FirstWeekOfYear | Optional. A constant that specifies the first week of the year. |
Settings
The firstdayofweek argument has these settings.
Constant | Value | Description |
---|---|---|
vbUseSystem | 0 | Use NLS API setting. |
vbSunday | 1 | Sunday (default) |
vbMonday | 2 | Monday |
vbTuesday | 3 | Tuesday |
vbWednesday | 4 | Wednesday |
vbThursday | 5 | Thursday |
vbFriday | 6 | Friday |
vbSaturday | 7 | Saturday |
The firstweekofyear argument has these settings.
Constant | Value | Description |
---|---|---|
vbUseSystem | 0 | Use NLS API setting. |
vbFirstJan1 | 1 | Start with week in which January 1 occurs (default). |
vbFirstFourDays | 2 | Start with the first week that has at least four days in the year. |
vbFirstFullWeek | 3 | Start with the first full week of the year. |
Remarks
To format | Do this |
---|---|
Numbers | Use predefined named numeric formats or create user-defined numeric formats. |
Dates and times | Use predefined named date/time formats or create user-defined date/time formats. |
Date and time serial numbers | Use date and time formats or numeric formats. |
Strings | Create your own user-defined string formats. |
Format truncates format to 257 characters.
If you try to format a number without specifying format, Format provides functionality similar to the Str function, although it is internationally aware. However, positive numbers formatted as strings using Format don’t include a leading space reserved for the sign of the value; those converted using Str retain the leading space.
If you are formatting a non-localized numeric string, you should use a user-defined numeric format to ensure that you get the look you want.
[!NOTE]
If the Calendar property setting isGregorian
and format specifies date formatting, the supplied expression must beGregorian
. If the Visual Basic Calendar property setting isHijri
, the supplied expression must beHijri
.
If the calendar is Gregorian, the meaning of format expression symbols is unchanged. If the calendar is Hijri, all date format symbols (for example, dddd, mmmm, yyyy ) have the same meaning but apply to the Hijri calendar. Format symbols remain in English; symbols that result in text display (for example, AM and PM) display the string (English or Arabic) associated with that symbol. The range of certain symbols changes when the calendar is Hijri.
Date symbols
Symbol | Range |
---|---|
d | 1-31 (Day of month, with no leading zero) |
dd | 01-31 (Day of month, with a leading zero) |
w | 1-7 (Day of week, starting with Sunday = 1) |
ww | 1-53 (Week of year, with no leading zero; Week 1 starts on Jan 1) |
m | 1-12 (Month of year, with no leading zero, starting with January = 1) |
mm | 01-12 (Month of year, with a leading zero, starting with January = 01) |
mmm | Displays abbreviated month names (Hijri month names have no abbreviations) |
mmmm | Displays full month names |
y | 1-366 (Day of year) |
yy | 00-99 (Last two digits of year) |
yyyy | 100-9999 (Three- or Four-digit year) |
Time symbols
Symbol | Range |
---|---|
h | 0-23 (1-12 with «AM» or «PM» appended) (Hour of day, with no leading zero) |
hh | 00-23 (01-12 with «AM» or «PM» appended) (Hour of day, with a leading zero) |
n | 0-59 (Minute of hour, with no leading zero) |
nn | 00-59 (Minute of hour, with a leading zero) |
m | 0-59 (Minute of hour, with no leading zero). Only if preceded by h or hh |
mm | 00-59 (Minute of hour, with a leading zero). Only if preceded by h or hh |
s | 0-59 (Second of minute, with no leading zero) |
ss | 00-59 (Second of minute, with a leading zero) |
Example
This example shows various uses of the Format function to format values using both named formats and user-defined formats. For the date separator (/), time separator (:), and AM/ PM literal, the actual formatted output displayed by your system depends on the locale settings on which the code is running. When times and dates are displayed in the development environment, the short time format and short date format of the code locale are used. When displayed by running code, the short time format and short date format of the system locale are used, which may differ from the code locale. For this example, English/U.S. is assumed. MyTime
and MyDate
are displayed in the development environment using current system short time setting and short date setting.
Dim MyTime, MyDate, MyStr MyTime = #17:04:23# MyDate = #January 27, 1993# ' Returns current system time in the system-defined long time format. MyStr = Format(Time, "Long Time") ' Returns current system date in the system-defined long date format. MyStr = Format(Date, "Long Date") MyStr = Format(MyTime, "h:m:s") ' Returns "17:4:23". MyStr = Format(MyTime, "hh:mm:ss am/pm") ' Returns "05:04:23 pm". MyStr = Format(MyTime, "hh:mm:ss AM/PM") ' Returns "05:04:23 PM". MyStr = Format(MyDate, "dddd, mmm d yyyy") ' Returns "Wednesday, Jan 27 1993". ' If format is not supplied, a string is returned. MyStr = Format(23) ' Returns "23". ' User-defined formats. MyStr = Format(5459.4, "##,##0.00") ' Returns "5,459.40". MyStr = Format(334.9, "###0.00") ' Returns "334.90". MyStr = Format(5, "0.00%") ' Returns "500.00%". MyStr = Format("HELLO", "<") ' Returns "hello". MyStr = Format("This is it", ">") ' Returns "THIS IS IT".
Different formats for different numeric values
A user-defined format expression for numbers can have from one to four sections separated by semicolons. If the format argument contains one of the named numeric formats, only one section is allowed.
If you use | The result is |
---|---|
One section only | The format expression applies to all values. |
Two sections | The first section applies to positive values and zeros, the second to negative values. |
Three sections | The first section applies to positive values, the second to negative values, and the third to zeros. |
Four sections | The first section applies to positive values, the second to negative values, the third to zeros, and the fourth to Null values. |
If you include semicolons with nothing between them, the missing section is printed using the format of the positive value. For example, the following format displays positive and negative values using the format in the first section and displays «Zero» if the value is zero.
Different formats for different string values
A format expression for strings can have one section or two sections separated by a semicolon (;).
If you use | The result is |
---|---|
One section only | The format applies to all string data. |
Two sections | The first section applies to string data, the second to Null values and zero-length strings («»). |
Named date/time formats
The following table identifies the predefined date and time format names.
Format name | Description |
---|---|
General Date | Display a date and/or time, for example, 4/3/93 05:34 PM. If there is no fractional part, display only a date, for example, 4/3/93. If there is no integer part, display time only, for example, 05:34 PM. Date display is determined by your system settings. |
Long Date | Display a date according to your system’s long date format. |
Medium Date | Display a date using the medium date format appropriate for the language version of the host application. |
Short Date | Display a date using your system’s short date format. |
Long Time | Display a time using your system’s long time format; includes hours, minutes, seconds. |
Medium Time | Display time in 12-hour format using hours and minutes and the AM/PM designator. |
Short Time | Display a time using the 24-hour format, for example, 17:45. |
Named numeric formats
The following table identifies the predefined numeric format names.
Format name | Description |
---|---|
General Number | Display number with no thousand separator. |
Currency | Display number with thousand separator, if appropriate; display two digits to the right of the decimal separator. Output is based on system locale settings. |
Fixed | Display at least one digit to the left and two digits to the right of the decimal separator. |
Standard | Display number with thousand separator, at least one digit to the left and two digits to the right of the decimal separator. |
Percent | Display number multiplied by 100 with a percent sign (%) appended to the right; always display two digits to the right of the decimal separator. |
Scientific | Use standard scientific notation. |
Yes/No | Display No if number is 0; otherwise, display Yes. |
True/False | Display False if number is 0; otherwise, display True. |
On/Off | Display Off if number is 0; otherwise, display On. |
User-defined string formats
Use any of the following characters to create a format expression for strings.
Character | Description |
---|---|
@ | Character placeholder. Display a character or a space. If the string has a character in the position where the at symbol (@) appears in the format string, display it; otherwise, display a space in that position. Placeholders are filled from right to left unless there is an exclamation point character (!) in the format string. |
& | Character placeholder. Display a character or nothing. If the string has a character in the position where the ampersand (&) appears, display it; otherwise, display nothing. Placeholders are filled from right to left unless there is an exclamation point character (!) in the format string. |
< | Force lowercase. Display all characters in lowercase format. |
> | Force uppercase. Display all characters in uppercase format. |
! | Force left to right fill of placeholders. The default is to fill placeholders from right to left. |
User-defined date/time formats
The following table identifies characters you can use to create user-defined date/time formats.
Character | Description |
---|---|
(:) | Time separator. In some locales, other characters may be used to represent the time separator. The time separator separates hours, minutes, and seconds when time values are formatted. The actual character used as the time separator in formatted output is determined by your system settings. |
(/) | Date separator. In some locales, other characters may be used to represent the date separator. The date separator separates the day, month, and year when date values are formatted. The actual character used as the date separator in formatted output is determined by your system settings. |
c | Display the date as ddddd and display the time as ttttt , in that order. Display only date information if there is no fractional part to the date serial number; display only time information if there is no integer portion. |
d | Display the day as a number without a leading zero (1–31). |
dd | Display the day as a number with a leading zero (01–31). |
ddd | Display the day as an abbreviation (Sun–Sat). Localized. |
dddd | Display the day as a full name (Sunday–Saturday). Localized. |
ddddd | Display the date as a complete date (including day, month, and year), formatted according to your system’s short date format setting. The default short date format is m/d/yy . |
dddddd | Display a date serial number as a complete date (including day, month, and year) formatted according to the long date setting recognized by your system. The default long date format is mmmm dd, yyyy . |
w | Display the day of the week as a number (1 for Sunday through 7 for Saturday). |
ww | Display the week of the year as a number (1–54). |
m | Display the month as a number without a leading zero (1–12). If m immediately follows h or hh , the minute rather than the month is displayed. |
mm | Display the month as a number with a leading zero (01–12). If m immediately follows h or hh , the minute rather than the month is displayed. |
mmm | Display the month as an abbreviation (Jan–Dec). Localized. |
mmmm | Display the month as a full month name (January–December). Localized. |
q | Display the quarter of the year as a number (1–4). |
y | Display the day of the year as a number (1–366). |
yy | Display the year as a 2-digit number (00–99). |
yyyy | Display the year as a 4-digit number (100–9999). |
h | Display the hour as a number without a leading zero (0–23). |
hh | Display the hour as a number with a leading zero (00–23). |
n | Display the minute as a number without a leading zero (0–59). |
nn | Display the minute as a number with a leading zero (00–59). |
s | Display the second as a number without a leading zero (0–59). |
ss | Display the second as a number with a leading zero (00–59). |
ttttt | Display a time as a complete time (including hour, minute, and second), formatted using the time separator defined by the time format recognized by your system. A leading zero is displayed if the leading zero option is selected and the time is before 10:00 A.M. or P.M. The default time format is h:mm:ss . |
AM/PM | Use the 12-hour clock and display an uppercase AM with any hour before noon; display an uppercase PM with any hour between noon and 11:59 P.M. |
am/pm | Use the 12-hour clock and display a lowercase AM with any hour before noon; display a lowercase PM with any hour between noon and 11:59 P.M. |
A/P | Use the 12-hour clock and display an uppercase A with any hour before noon; display an uppercase P with any hour between noon and 11:59 P.M. |
a/p | Use the 12-hour clock and display a lowercase A with any hour before noon; display a lowercase P with any hour between noon and 11:59 P.M. |
AMPM | Use the 12-hour clock and display the AM string literal as defined by your system with any hour before noon; display the PM string literal as defined by your system with any hour between noon and 11:59 P.M. AMPM can be either uppercase or lowercase, but the case of the string displayed matches the string as defined by your system settings. The default format is AM/PM. If your system is set to 24-hour clock, the string is typical set to a zero-length string. |
User-defined numeric formats
The following table identifies characters you can use to create user-defined number formats.
Character | Description |
---|---|
None | Display the number with no formatting. |
(0) | Digit placeholder. Display a digit or a zero. If the expression has a digit in the position where the 0 appears in the format string, display it; otherwise, display a zero in that position.If the number has fewer digits than there are zeros (on either side of the decimal) in the format expression, display leading or trailing zeros. If the number has more digits to the right of the decimal separator than there are zeros to the right of the decimal separator in the format expression, round the number to as many decimal places as there are zeros. If the number has more digits to the left of the decimal separator than there are zeros to the left of the decimal separator in the format expression, display the extra digits without modification. |
(#) | Digit placeholder. Display a digit or nothing. If the expression has a digit in the position where the # appears in the format string, display it; otherwise, display nothing in that position. This symbol works like the 0 digit placeholder, except that leading and trailing zeros aren’t displayed if the number has the same or fewer digits than there are # characters on either side of the decimal separator in the format expression. |
(.) | Decimal placeholder. In some locales, a comma is used as the decimal separator. The decimal placeholder determines how many digits are displayed to the left and right of the decimal separator. If the format expression contains only number signs to the left of this symbol, numbers smaller than 1 begin with a decimal separator. To display a leading zero displayed with fractional numbers, use 0 as the first digit placeholder to the left of the decimal separator. The actual character used as a decimal placeholder in the formatted output depends on the Number Format recognized by your system. |
(%) | Percentage placeholder. The expression is multiplied by 100. The percent character (%) is inserted in the position where it appears in the format string. |
(,) | Thousand separator. In some locales, a period is used as a thousand separator. The thousand separator separates thousands from hundreds within a number that has four or more places to the left of the decimal separator. Standard use of the thousand separator is specified if the format contains a thousand separator surrounded by digit placeholders (0 or #). Two adjacent thousand separators or a thousand separator immediately to the left of the decimal separator (whether or not a decimal is specified) means «scale the number by dividing it by 1000, rounding as needed.» For example, you can use the format string «##0,,» to represent 100 million as 100. Numbers smaller than 1 million are displayed as 0. Two adjacent thousand separators in any position other than immediately to the left of the decimal separator are treated simply as specifying the use of a thousand separator. The actual character used as the thousand separator in the formatted output depends on the Number Format recognized by your system. |
(:) | Time separator. In some locales, other characters may be used to represent the time separator. The time separator separates hours, minutes, and seconds when time values are formatted. The actual character used as the time separator in formatted output is determined by your system settings. |
(/) | Date separator. In some locales, other characters may be used to represent the date separator. The date separator separates the day, month, and year when date values are formatted. The actual character used as the date separator in formatted output is determined by your system settings. |
(E- E+ e- e+) | Scientific format. If the format expression contains at least one digit placeholder (0 or #) to the right of E-, E+, e-, or e+, the number is displayed in scientific format and E or e is inserted between the number and its exponent. The number of digit placeholders to the right determines the number of digits in the exponent. Use E- or e- to place a minus sign next to negative exponents. Use E+ or e+ to place a minus sign next to negative exponents and a plus sign next to positive exponents. |
— + $ ( ) | Display a literal character. To display a character other than one of those listed, precede it with a backslash ( ) or enclose it in double quotation marks (» «). |
() | Display the next character in the format string. To display a character that has special meaning as a literal character, precede it with a backslash ( ). The backslash itself isn’t displayed. Using a backslash is the same as enclosing the next character in double quotation marks. To display a backslash, use two backslashes (\ ). Examples of characters that can’t be displayed as literal characters are the date-formatting and time-formatting characters (a, c, d, h, m, n, p, q, s, t, w, y, /, and :), the numeric-formatting characters (#, 0, %, E, e, comma, and period), and the string-formatting characters (@, &, <, >, and !). |
(«ABC») | Display the string inside the double quotation marks (» «). To include a string in format from within code, you must use Chr(34) to enclose the text (34 is the character code for a quotation mark («)). |
See also
- Functions (Visual Basic for Applications)
[!includeSupport and feedback]
VBA Format function in Excel is categorized as a Text/String function in VBA. It is a built-in function in MS Office Excel. VBA Format function returns a formatted string from a string expression. This function has one required parameter and three optional parameters. If Format argument is left blank, then the function behaves like the CSTR function.
This function use as a VBA function and can’t use as a Excel Worksheet function. The VBA Format function can be used in either procedure or function in a VBA editor window in Excel. We can use this VBA Format function any number of times in any number of procedures or functions. In the following section we learn what is the syntax and parameters of the Format function, where we can use this Format function and real-time examples in VBA.
Table of Contents:
- Overview
- Syntax of VBA Format Function
- Parameters or Arguments
- VBA Date Formats
- VBA Number Formats
- VBA Text Formats
- Enumeration values of the FirstDayOfWeek
- Enumeration values of the FirstWeekOfYear
- Where we can apply or use the VBA Format Function?
- Example 1: Format Date and Time
- Example 2: Format Numbers and currency
- Example 3: Format Text/String
- Example 4: User Defined Format
- Instructions to Run VBA Macro Code
- Other Useful Resources
The syntax of the VBA Format function is
Format(Expression, [Format], [FirstDayOfWeek],[FirstWeekOfYear])
Note: This Format function returns a string.
Parameters or Arguments
This function has one mandatory parameter and three optional parameters for the Format Function.
Where
Expression: The Expression is a mandatory argument. It represents an expression which you want to format.
Format: The Format is an optional argument. It represents the user defined or below specified built-in format. It is applied to an Expression.
VBA Date Formats: Here are the following list of built-in Date formats.
Format | Description |
---|---|
General Date | It displays date as defined in your system general Date settings. It displays short date and short time. |
Long Date | It displays date as defined in your system Long Date settings |
Medium Date | It displays date as defined in your system Medium Date settings |
Short Date | It displays date as defined in your system Short Date settings |
Long Time | It displays time as defined in your system Long time settings |
Medium Time | It displays time as defined in your system Medium time settings |
Short Time | It displays time as defined in your system Short time settings |
VBA Number Formats: Here are the following list of built-in Number formats.
Format | Description |
---|---|
General Number | It displays a number without any thousand separators. |
Currency | It displays a number with thousand separators and two decimal places. |
Euro | It displays a number with the euro currency symbol. |
Fixed | It displays at least one integer digit and two decimal places number. |
Standard | It displays a number with thousand separators, at least one integer digit and two decimal places. |
Percent | It displays the number to the percentage form and adds % sign and rounds it up to two decimal places. |
Scientific | It displays a number in scientific notation. |
Yes/No | It displays No if the number is equal to zero or Yes otherwise. |
True/False | It displays False if the number is equal to zero or True otherwise. |
On/Off | It displays Off if the number is equal to zero or On otherwise. |
VBA Text Formats: Here are the following list of Text and Memo formats.
Format Symbol | Description |
---|---|
@ | Text character is required. |
& | Text character is not required. |
< | Convert all characters to lowercase. |
> | Convert all characters to uppercase. |
FirstDayOfWeek: The FirstDayOfWeek is an optional argument. It represents the first day of week. This argument uses the default value vbSunday (Sunday).
VBA Constant | Value | Description |
---|---|---|
vbUseSystem | 0 | Uses the NLS API setting (The first day of the week specified in system settings) |
VbSunday | 1 | Sunday |
vbMonday | 2 | Monday |
vbTuesday | 3 | Tuesday |
vbWednesday | 4 | Wednesday |
vbThursday | 5 | Thursday |
vbFriday | 6 | Friday |
vbSaturday | 7 | Saturday |
FirstWeekOfYear: The FirstWeekOfYear is an optional argument. It represents the first week of the year. This argument uses the default value vbFirstJan1 (1st January).
VBA Constant | Value | Description |
---|---|---|
vbUseSystem | 0 | Uses the NLS API setting. |
vbFirstJan1 | 1 | The week that conatins 1st Jan in the year. |
vbFirstFourDays | 2 | The first week that conatins atleast 4 days in the year. |
vbFirstFullWeek | 3 | The first full week of the year. |
Where we can apply or use the VBA Format Function?
We can use this VBA Format function in MS Office 365, MS Excel 2016, MS Excel 2013, 2011, Excel 2010, Excel 2007, Excel 2003, Excel 2016 for Mac, Excel 2011 for Mac, Excel Online, Excel for iPhone, Excel for iPad, Excel for Android tablets and Excel for Android Mobiles.
Example 1: Format Date and Time
Here is a simple example of the VBA Format function. Here you can see multiple examples of VBA Date and Time Format function.
'Format Date and Time Sub VBA_Format_Function_Ex1() Dim sDate As String, sTime As String Dim sDateTime As String Dim sOutput As String, sOutput1 As String, sOutput2 As String sDate = Date: sTime = Time sDateTime = sDate & " " & sTime sOutput = Format(sDateTime) MsgBox "General Date & Time Format : " & vbCrLf & sOutput, vbInformation, "VBA Format Function" '-------------------------------------------------------------------------------------- sOutput1 = Format(sDate, "Medium Date") sOutput2 = Format(sTime, "Medium time") MsgBox "Medium Date Format : " & sOutput1 & vbCrLf & "Medium Time Format : " & sOutput2, vbInformation, "VBA Format Function" '-------------------------------------------------------------------------------------- sOutput1 = Format(sDate, "Long Date") sOutput2 = Format(sTime, "Long time") MsgBox "Long Date Format : " & sOutput1 & vbCrLf & "Long Time Format : " & sOutput2, vbInformation, "VBA Format Function" '-------------------------------------------------------------------------------------- sOutput1 = Format(sDate, "dddd mm/dd/yyyy") sOutput2 = Format(sTime, "hh:mm:ss AMPM") MsgBox "User defined Date Format : " & sOutput1 & vbCrLf & "User defined Time Format : " & sOutput2, vbInformation, "VBA Format Function" End Sub
Output: Here is the screen shot of the first example output.
Example 2: Format Numbers and Currency
Here is a simple example of the VBA Format function. Here you can see multiple examples of VBA Number and Currency Format function.
'Format Numbers and currencies Sub VBA_Format_Function_Ex2() Dim sValue As String, sValue1 As String Dim sOutput As String sValue = 0.1234: sValue1 = 12345 sOutput = Format(sValue) ' General Number Format MsgBox "General Number Format : " & sOutput, vbInformation, "VBA Format Function" '-------------------------------------------------------------------------------------- sOutput = Format(sValue1, "Standard") ' MsgBox "Standard Format : " & sOutput, vbInformation, "VBA Format Function" '-------------------------------------------------------------------------------------- sOutput = Format(sValue1, "Fixed") ' MsgBox "Fixed Format : " & sOutput, vbInformation, "VBA Format Function" '-------------------------------------------------------------------------------------- sOutput = Format(sValue, "Currency") ' MsgBox "Currency Format : " & sOutput, vbInformation, "VBA Format Function" '-------------------------------------------------------------------------------------- sOutput = Format(sValue, "Percent") ' MsgBox "Percent Format : " & sOutput, vbInformation, "VBA Format Function" End Sub
Output: Here is the screen shot of the second example output.
Example 3: Format Text/String
Here is a simple example of the VBA Format function. Here you can see multiple examples of VBA Text/String Format function.
'Format Text/String Sub VBA_Format_Function_Ex3() Dim sValue As String, sValue1 As String Dim sOutput As String sValue = "Welcome to VBAF1": sValue1 = "999999999" sOutput = Format(sValue, ">") MsgBox "User defined Format : " & sOutput, vbInformation, "VBA Format Function" '-------------------------------------------------------------------------------------- sOutput = Format(sValue, "<") MsgBox "User defined Format : " & sOutput, vbInformation, "VBA Format Function" '-------------------------------------------------------------------------------------- sOutput = Format(sValue1, "@@@@@@@@@") MsgBox "User defined Format : " & sOutput, vbInformation, "VBA Format Function" '-------------------------------------------------------------------------------------- sOutput = Format(sValue1, "@@@-@@@-@@@") MsgBox "User defined Format : " & sOutput, vbInformation, "VBA Format Function" '-------------------------------------------------------------------------------------- sOutput = Format(sValue1, "@@@") MsgBox "User defined Format : " & sOutput, vbInformation, "VBA Format Function" '-------------------------------------------------------------------------------------- sOutput = Format(sValue1, "@@@-&&&-@@@") MsgBox "User defined Format : " & sOutput, vbInformation, "VBA Format Function" End Sub
Output: Here is the screen shot of the third example output.
Example 4: User Defined Format
Here is a simple example of the VBA Format function. Here you can see multiple examples of VBA User Defined Format function.
'User Defined Format Sub VBA_Format_Function_Ex4() Dim sValue As String, sValue1 As String Dim sOutput As String sValue = 12345.678: sValue1 = 0.1357 sOutput = Format(sValue, "0.000") MsgBox "User defined Format : " & sOutput, vbInformation, "VBA Format Function" '-------------------------------------------------------------------------------------- sOutput = Format(sValue, "##,##0") ' MsgBox "User defined Format : " & sOutput, vbInformation, "VBA Format Function" '-------------------------------------------------------------------------------------- sOutput = Format(sValue, "$##,##0.00") ' MsgBox "User defined Format : " & sOutput, vbInformation, "VBA Format Function" '-------------------------------------------------------------------------------------- sOutput = Format(sValue, "£##,##0.00") ' MsgBox "User defined Format : " & sOutput, vbInformation, "VBA Format Function" '-------------------------------------------------------------------------------------- sOutput = Format(sValue1, "0%") ' MsgBox "User defined Format : " & sOutput, vbInformation, "VBA Format Function" '-------------------------------------------------------------------------------------- sOutput = Format(sValue1, "0.00%") ' MsgBox "User defined Format : " & sOutput, vbInformation, "VBA Format Function" End Sub
Output: Here is the screen shot of the fourth example output.
Instructions to Run VBA Macro Code or Procedure:
You can refer the following link for the step by step instructions.
Instructions to run VBA Macro Code
Other Useful Resources:
Click on the following links of the useful resources. These helps to learn and gain more knowledge.
VBA Tutorial VBA Functions List VBA Arrays in Excel Blog
VBA Editor Keyboard Shortcut Keys List VBA Interview Questions & Answers
In this Article
- Format Function
- Format Numbers with Predefined Formats
- Format Numbers with User-Defined Formats
- Format Numbers Depending on the Values
- Format Dates with Predefined Formats
- Format Dates with User-Defined Formats
- Format for Better Readability
- Format Patterns in Worksheet Cells
- Format Patterns with Text Formula
This tutorial will demonstrate how to use the Format function.
Format Function
Format Numbers with Predefined Formats
Format function can convert a number to string formatted with predefined named numeric formats. Those predefined formats are Currency, Fixed, Standard, Percent, Scientific, Yes/No, True/False, and On/Off.
Sub FormatExample_1()
MsgBox Format(1234567.8) 'Result is: 1234567.8
'Format just leaves the number as it is
MsgBox Format(1234567.8, "Currency") 'Result is: $1,234,567.80
'Currency uses the systems currency settings
MsgBox Format(1234567.8, "Fixed") 'Result is: 1234567.80
'Fixed: At least one digit before decimal point and
'uses system settings for the decimal part
MsgBox Format(1234567.8, "Standard") 'Result is: 1,234,567.80
'Standard: Thousands separators and standard system
MsgBox Format(1234567.8, "Percent") 'Result is: 123456780.00%
'Percent, multiplies by 100 with % and standard system.
MsgBox Format(1234567.8, "Scientific") 'Result is: 1.23E+06
'Scientific notation
MsgBox Format(1234567.8, "Yes/No") 'Result is: Yes
'No if the number is zero
MsgBox Format(1234567.8, "True/False") 'Result is: True
'False if the number is equal to zero
MsgBox Format(1234567.8, "On/Off") 'Result is: On
'Off if the number is zero
End Sub
Format Numbers with User-Defined Formats
Format function can convert a number to a string, formatted user-defined numeric formats. 0 is a digit placeholder that displays a digit or zero. # is a digit placeholder that displays a digit or nothing. A dot (.) is the decimal placeholder, % is the percentage placeholder and comma (,) is the thousands separator. Text can be added in the format using double quotes (“”) and a single character can be added if it is used after a backslash ().
Sub FormatExample_2()
MsgBox Format(7.8, "000.00") 'Result is: 007.80
MsgBox Format(12347.8356, "000.00") 'Result is: 12347.84
MsgBox Format(7.8, "###.##") 'Result is: 7.8
MsgBox Format(12347.8356, "###.##") 'Result is: 12347.84
MsgBox Format(7.8, "$.00") 'Result is: $7.80
MsgBox Format(1237.835, "ABA0.00") 'Result is: ABA1237.84
MsgBox Format(12347.8356, "000.00%") 'Result is: 1234783.56%
MsgBox Format(12347.8356, "%000.00") 'Result is: %12347.84
End Sub
Format Numbers Depending on the Values
Format function can have different sections using different format rules for positive numbers, negative numbers, zero, and Null. These sections are separated by a semicolon.
Sub FormatExample_3()
MsgBox Format(7.8, "000.00;(000.00);zero;nothing") 'Result is: 007.80
MsgBox Format(-7.8, "000.00;(000.00);zero;nothing") 'Result is: (007.80)
MsgBox Format(0, "000.00;(000.00);zero;nothing") 'Result is: zero
MsgBox Format(Null, "000.00;(000.00);zero;nothing") 'Result is: nothing
End Sub
Format Dates with Predefined Formats
Format function can format dates with different predefined formats. Those formats are long, medium, and short date and also long, medium, and short time.
Sub FormatExample_4()
Dim DateEx As Date
DateEx = #4/18/2020 7:35:56 PM#
MsgBox Format(DateEx, "General Date") 'Result is: 4/18/2020 7:35:56 PM
MsgBox Format(DateEx, "Long Date") 'Result is: Saturday, April 18, 2020
MsgBox Format(DateEx, "Medium Date") 'Result is: 18-Apr-20
MsgBox Format(DateEx, "Short Date") 'Result is: 4/18/2020
MsgBox Format(DateEx, "Long Time") 'Result is: 7:35:56 PM
MsgBox Format(DateEx, "Medium Time") 'Result is: 07:35 PM
MsgBox Format(DateEx, "Short Time") 'Result is: 19:35
End Sub
Format Dates with User-Defined Formats
Format function can format dates with user-defined formats. Characters like d, m, y, w, q can be used to create custom date formats.
Sub FormatExample_5()
Dim DateEx As Date
DateEx = #4/18/2020 7:35:56 PM#
MsgBox Format(DateEx, "m/d/yy") 'Result is: 4/18/2020
MsgBox Format(DateEx, "mm-dd-yy") 'Result is: 04-18-2020
MsgBox Format(DateEx, "mmm-dd-yy") 'Result is: Apr-18-2020
MsgBox Format(DateEx, "mmmm-dd-yy") 'Result is: April-18-2020
MsgBox Format(DateEx, "mm-ddd-yy") 'Result is: 04-Sat-2020
MsgBox Format(DateEx, "mm-dddd-yy") 'Result is: 04-Saturday-2020
MsgBox Format(DateEx, "y")
'Result is: 109
'number of day in year 1-366
MsgBox Format(DateEx, "ww")
'Result is: 16
'number of week in year 1-52
MsgBox Format(DateEx, "q")
'Result is: 2
'quarter in year 1-4
End Sub
Characters like h, n, s and am, pm combinations can be used to create custom time formats.
Sub FormatExample_6()
Dim DateEx As Date
DateEx = #4/18/2020 7:06:05 PM#
MsgBox Format(DateEx, "h:n:s") 'Result is: 19:6:5
MsgBox Format(DateEx, "hh:nn:ss") 'Result is: 19:06:05
MsgBox Format(DateEx, "hh:nn:ss am/pm") 'Result is: 07:06:05 pm
MsgBox Format(DateEx, "hh:nn:ss AM/PM") 'Result is: 07:06:05 PM
MsgBox Format(DateEx, "hh:nn:ss a/p") 'Result is: 07:06:05 p
MsgBox Format(DateEx, "hh:nn:ss A/P") 'Result is: 07:06:05 P
End Sub
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
Format for Better Readability
Format function can format strings or numbers for better readability. @ is a character placeholder used to display a character or space. & is a character placeholder used to display a character or nothing. ! can be used to use character placeholders from left to right and < or > can be used to enforce lower or upper case. Can be useful in formatting telephone numbers or other big numbers without changing the original value.
Sub FormatExample_7()
Dim StrEx As String
StrEx = "ABCdef"
MsgBox Format(StrEx, "-@@@-@@-@@") 'Result is: - AB-Cd-ef
MsgBox Format(StrEx, "-&&&-&&-&&") 'Result is: -AB-Cd-ef
'Starts from right to left.
MsgBox Format(StrEx, "-@@@-@@-@@-@@") 'Result is: - -AB-Cd-ef
MsgBox Format(StrEx, "-&&&-&&-&&-&&") 'Result is: --AB-Cd-ef
'Starts from right to left. When out of characters @ adds spaces and & adds nothing
MsgBox Format(StrEx, "!-@@@-@@-@@-@@") 'Result is: -ABC-de-f -
MsgBox Format(StrEx, "!-&&&-&&-&&-&&") 'Result is: -ABC-de-f
'Starts from left to right because of the !
MsgBox Format(StrEx, ">") 'Result is: ABCDEF
MsgBox Format(StrEx, "<") 'Result is: abcdef
MsgBox Format(1234567890, "@@@-@@@-@@@@") 'Result is: 123-456-7890
MsgBox Format(1234567890, "@@@@-@@@-@@@") 'Result is: 1234-567-890
End Sub
Format Patterns in Worksheet Cells
Format function can be used in VBA code and also in worksheets cells. Select the cell or range of cells and follow the menu entry Format Cells > Custom. There are many user-defined formats and also the user can create his own custom formats.
VBA Programming | Code Generator does work for you!
AutoMacro | Ultimate VBA Add-in | Click for Free Trial!
Format Patterns with Text Formula
The format function can directly change the format of a value inside VBA code. We can also use excel Text formula to get the same result using WorksheetFunction.Text.
Sub FormatExample_8()
MsgBox Format(7.8, "000.00")
'Result is: 007.80
MsgBox WorksheetFunction.Text(7.8, "000.00")
'Result is: 007.80
MsgBox Format(7.8, "###.##")
'Result is: 7.8
MsgBox WorksheetFunction.Text(7.8, "###.##")
'Result is: 7.8
End Sub
Excel VBA Format Function
Format function in VBA one may use to format the given values in the desired format. For example, one can use this function for formatting dates or numbers or any trigonometric values. This function has two mandatory arguments: input taken in the form of a string, and the second argument 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%.
In VBA, we need to use the function “FORMAT” to apply the format to cells. Excel formattingFormatting is a useful feature in Excel that allows you to change the appearance of the data in a worksheet. Formatting can be done in a variety of ways. For example, we can use the styles and format tab on the home tab to change the font of a cell or a table.read more is one of the important concepts to master. We all use the common formatting techniques in our daily work: date, time, number, and other important formatting codes. We press the format excel cellFormatting cells is an important technique to master because it makes any data presentable, crisp, and in the user’s preferred format. The formatting of the cell depends upon the nature of the data present.read more option in regular Excel worksheets and perform the formatting duty by applying the appropriate formatting code. However, in VBA, this is not as straightforward as our worksheet technique.
Table of contents
- Excel VBA Format Function
- Syntax
- How to Use?
- #1 – Currency Format
- #2 – Fixed Format
- #3 – Percent Format
- #4 – User-Defined Formats
- #5 – Date FORMAT
- Things to Remember
- Recommended Articles
Syntax
- Expression: This is nothing but the value we want to format. In VAB technicality, it is called Expression.
- [Format]: What format do you want to apply to the selected expression? We have two kinds of formatting here: user-defined format and built-in format.
- Here, we have VBA date, number, and text formats.
- VBA date formats have a short date, long date, medium date, and general date.
- Number formats have currency, standard, percentage, scientific, yes or no, true or false, and on or off.
- [First Day of the Week]: What is the first day of your week? We can select any day from the list. Below is the list of days and appropriate codes.
- [First Week of the Year]: What is the year’s first week? It specifies the week it should use as the year’s first week.
How to Use?
You can download this VBA Format Template here – VBA Format Template
Let us apply this function practically to understand the functionality of the FORMAT function. Assume you have the number 8072.56489. You want to apply number formatting to it. Follow the below steps to apply number formatting to it.
Step 1: Start an excel macroA macro in excel is a series of instructions in the form of code that helps automate manual tasks, thereby saving time. Excel executes those instructions in a step-by-step manner on the given data. For example, it can be used to automate repetitive tasks such as summation, cell formatting, information copying, etc. thereby rapidly replacing repetitious operations with a few clicks.
read more and define the variable as a “string” data type.
Code:
Sub Worksheet_Function_Example1() Dim K As String End Sub
Step 2: Assign a value to k as our number, 8072.56489.
Code:
Sub Worksheet_Function_Example1() Dim K As String K = 8072.56489 End Sub
Step 3: Show the “k” 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 Worksheet_Function_Example1() Dim K As String K = 8072.56489 MsgBox K End Sub
Step 4: If you run this macro, we will get the below result.
The result is as it is, we assigned the value to variable “k.” But we need to apply some formatting to this number to make it beautiful.
Step 5: Instead of directly assigning a value to “k,“ let us use the FORMAT function.
Code:
Sub Worksheet_Function_Example1() Dim K As String K = Format( MsgBox K End Sub
Step 6: Now, for Expression, assign the number 8072.56489.
Code:
Sub Worksheet_Function_Example1() Dim K As String K = Format(8072.56489, MsgBox K End Sub
Step 7: We can use a built-in format or our own formatting code in the formatting option. Now, we will use a built-in formatting style as “Standard.”
Code:
Sub Worksheet_Function_Example1() Dim K As String K = Format(8072.56489, "Standard") MsgBox K End Sub
Step 8: Now, run this code and see the result of the message box.
We have comma (,) as thousand separators and decimal rounds up to two digits only.
Like this, we can use many other built-in formatting styles to apply the formatting. Below are some of the codes we have applied.
#1 – Currency Format
Code:
Sub Worksheet_Function_Example2() Dim K As String K = Format(8072.56489, "Currency") MsgBox K End Sub
Result:
#2 – Fixed Format
Code:
Sub Worksheet_Function_Example3() Dim K As String K = Format(8072.56489, "Fixed") MsgBox K End Sub
Result:
#3 – Percent Format
Code:
Sub Worksheet_Function_Example4() Dim K As String K = Format(8072.56489, "Percent") MsgBox K End Sub
Result:
#4 – User-Defined Formats
Now, we will see some of the user-defined formats.
Code:
Sub Worksheet_Function_Example5() Dim K As String K = Format(8072.56489, "#.##") MsgBox K End Sub
Result:
Code:
Sub Worksheet_Function_Example5() Dim K As String K = Format(8072.56489, "#,##.##") MsgBox K End Sub
Result:
#5 – Date FORMAT
We have seen some important numbers of formatting techniques. We will have to use the FORMAT function to format the date in VBA.To format the date in VBA, we use the in-built FORMAT function that converts a date expression into the required format. In order to perform the function, one must enter a valid expression and format type.read more
We have written code to show the result of the date through the variable.
Code:
Sub Worksheet_Function_Example6() Dim K As String K = 13 - 3 - 2019 MsgBox K End Sub
When we run this code, we would not get an accurate date. Rather, the result is pathetic.
We need to assign the date format to get accurate dates. So, we first need to supply the date in double quotes and apply the date format.
Code:
Sub Worksheet_Function_Example6() Dim K As String K = Format("10 - 3 - 2019", "Long Date") MsgBox K End Sub
We run this code now. We will get a proper long date.
The “Long Date” is a built-in format. Similarly, you can use the “Short Date” and “Medium Date” options.
Things to Remember
- The value returned by the FORMAT function is the string.
- We can also use our date, time, and number formatting codes, like how we use them in worksheet formatting.
- The FORMAT is a VBA functionVBA functions serve the primary purpose to carry out specific calculations and to return a value. Therefore, in VBA, we use syntax to specify the parameters and data type while defining the function. Such functions are called user-defined functions.read more available only in VBA, not in the worksheet.
Recommended Articles
This article has been a guide to VBA Format Function. Here, we learned how to use VBA Format Function for currency, fixed, percentage, and date formatting, along with some practical examples and a downloadable Excel template. Below are some useful Excel articles related to VBA: –
- VBA Data Type
- VBA DIR Function
- VBA MOD
- Create VBA InputBox
Home / VBA / Top VBA Functions / VBA FORMAT Function (Syntax + Example)
The VBA FORMAT function is listed under the text category of VBA functions. When you use it in a VBA code, it returns a value formatted in the format you have specified. In simple words, you can use it to format an expression into a format that you can specify. There is one thing you need to note here the result that it returns is the string data type.
Format(Expression,[Format],[FirstDayOfWeek],[FirstWeekOfYear])
Arguments
- Expression: The expression that you want to format.
- [Format]: The format which you want to apply to the expression [This is an optional argument and if omitted VBA takes General by default].
- [FirstDayOfWeek]: A string to define the first day of the week [This is an optional argument and if omitted vbSunday by default].
- vbUseSystemDayOfWeek – As per the system settings.
- vbSunday – Sunday
- vbMonday – Monday
- vbTuesday – Tuesday
- vbWednesday – Wednesday
- vbThursday – Thursday
- vbFriday – Friday
- vbSaturday – Saturday
- [FirstWeekOfYear]: A string to define the first week of the year [This is an optional argument and if omitted vbFirstJan1 by default].
- vbSystem – As per the system settings.
- vbFirstJan1 – The week in which the 1st Day of Jan occurs.
- vbFirstFourDays – The first week that contains at least four days in the new year.
- vbFirstFullWeek – The first full week in the new year.
Example
To practically understand how to use VBA FORMAT function, you need to go through the below example where we have written a vba code by using it:
Sub example_FORMAT()
Range("B1").Value = Format(Range("A1"), "Currency")
Range("B2").Value = Format(Range("A2"), "Long Date")
Range("B3").Value = Format(Range("A3"), "True/False")
End Sub
In the above example, we have used FORMAT with three different predefined formats:
- Converting the value from cell A1 into a currency format.
- Converting the date from cell A2 into a long date.
- Converting the number from cell A3 into a boolean.
Notes
- You can also create your own format to use in the “format” argument.