Format vba excel описание

Преобразование чисел, дат и строк в настраиваемый текстовый формат из кода 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

Форматы даты, полученные с помощью разных по количеству наборов символа d

Символы для числовых форматов

Символ Описание
Точка (.) Десятичный разделитель.
Запятая (,) Разделитель групп разрядов. В отображаемых числах заполняется пробелом.
(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

Результаты форматирования строк с помощью специальных символов для функции Format

Форматы для различных значений одного выражения

Различные форматы для разных числовых значений

В выражении формата для чисел предусмотрено от одного до четырех разделов, отделяемых друг от друга точкой с запятой. Отображаемая строка зависит от значения, возвращенного параметром 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 is Gregorian and format specifies date formatting, the supplied expression must be Gregorian. If the Visual Basic Calendar property setting is Hijri, the supplied expression must be Hijri.

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.
VBA Format Function

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.
VBA Format Function

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.
VBA Format Function

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.
VBA Format Function

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!

automacro

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.

format cells custom menu screen

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

VBA-Format

Syntax

VBA Format Formula

  • 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.

VBA Format Table 1

  • [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.

VBA Format Table 2

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

VBA Format Example 1

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

VBA Format Example 1-1

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

VBA Format Example 1-2

Step 4: If you run this macro, we will get the below result.

VBA Format Example 1-3

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

VBA Format Example 1-4

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

VBA Format Example 1-5

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

VBA Format Example 1-6
Step 8: Now, run this code and see the result of the message box.

VBA Format Example 1-7

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

VBA Currency Format

Result:

VBA Currency Format 1

#2 – Fixed Format

Code:

Sub Worksheet_Function_Example3()
  Dim K As String

  K = Format(8072.56489, "Fixed")
  MsgBox K

End Sub

Fixed example 1

Result:

Fixed example 1-1

#3 – Percent Format

Code:

Sub Worksheet_Function_Example4()
  Dim K As String

  K = Format(8072.56489, "Percent")
  MsgBox K

End Sub

Percent Format

Result:

Percent Format 1

#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

Example 5

Result:

Example 5-1

Code:

Sub Worksheet_Function_Example5()
  Dim K As String

  K = Format(8072.56489, "#,##.##")
  MsgBox K

End Sub

Example 5-2

Result:

Example 5-3

#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.

Date Function 1

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.

Date Function 1-1

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:

  1. Converting the value from cell A1 into a currency format.
  2. Converting the date from cell A2 into a long date.
  3. Converting the number from cell A3 into a boolean.

Notes

  • You can also create your own format to use in the “format” argument.

Содержание

  1. VBA Format Function in Excel
  2. Syntax of VBA Format Function
  3. Parameters or Arguments
  4. Where we can apply or use the VBA Format Function?
  5. Example 1: Format Date and Time
  6. Example 2: Format Numbers and Currency
  7. Example 3: Format Text/String
  8. Example 4: User Defined Format
  9. Instructions to Run VBA Macro Code or Procedure:
  10. Other Useful Resources:
  11. Функция Format
  12. Синтаксис
  13. Параметры
  14. Примечания
  15. Символы даты
  16. Символы времени
  17. Пример
  18. Различные форматы для различных числовых значений
  19. Различные форматы для различных строковых значений
  20. Именованные форматы даты и времени
  21. Именованные числовые форматы
  22. Определяемые пользователем строковые форматы
  23. Определяемые пользователем форматы даты и времени
  24. Определяемые пользователем числовые форматы
  25. См. также
  26. Поддержка и обратная связь

VBA Format Function in Excel

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.

Syntax of VBA Format Function

The syntax of the VBA Format function is

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 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.

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.

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.

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.

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.

Other Useful Resources:

Click on the following links of the useful resources. These helps to learn and gain more knowledge.

Источник

Функция Format

Возвращает Variant (String), содержащий выражение expression, отформатированное в соответствии с инструкциями, включенными в выражение формата.

Хотите создавать решения, которые расширяют возможности Office на разнообразных платформах? Ознакомьтесь с новой моделью надстроек Office. Надстройки Office занимают меньше места по сравнению с надстройками и решениями VSTO, и вы можете создавать их, используя практически любую технологию веб-программирования, например HTML5, JavaScript, CSS3 и XML.

Синтаксис

Format(Expression, [ Format ], [ FirstDayOfWeek ], [ FirstWeekOfYear ])

Синтаксис функции Format состоит из следующих частей:

Часть Описание
Expression Обязательный атрибут. Любое допустимое выражение.
Format Необязательный атрибут. Допустимое именованное или определяемое пользователем выражение формата.
FirstDayOfWeek Необязательный атрибут. Константа, задающая первый день недели.
FirstWeekOfYear Необязательный атрибут. Константа, задающая первую неделю года.

Параметры

Аргумент firstdayofweekимеет эти параметры.

Константа Значение Описание
vbUseSystem 0 Использовать настройку API многоязыковой поддержки.
vbSunday 1 Воскресенье (по умолчанию)
vbMonday 2 Понедельник
vbTuesday 3 Вторник
vbWednesday 4 Среда
vbThursday 5 Четверг
vbFriday 6 Пятница
vbSaturday 7 Суббота

Аргумент firstweekofyearимеет эти параметры.

Константа Значение Описание
vbUseSystem 0 Использовать настройку API многоязыковой поддержки.
vbFirstJan1 1 Начать с недели, содержащей 1 января (по умолчанию).
vbFirstFourDays 2 Начать с первой недели, в которой имеется по крайней мере четыре дня в данном году.
vbFirstFullWeek 3 Начать с первой полной недели года.

Примечания

Чтобы отформатировать Сделайте следующее
Числа Используйте предопределенные именованные числовые форматы или создайте числовые форматы, определяемые пользователем.
Даты и время Используйте предопределенные именованные форматы даты и времени или создайте числовые форматы, определяемые пользователем.
Даты и время, представленные числами Используйте именованные форматы даты и времени или создайте числовые форматы.
Строки Создайте свои собственные определяемые пользователем строковые форматы.

Функция Format усекает format до 257 символов.

Если вы попытаетесь форматировать числа без задания атрибута format, функция Format предоставит функциональность, аналогичную функции Str, хотя и с поддержкой международных форматов. Однако положительные числа, отформатированные как строки с использованием функции Format, не будут включать начальный пробел, зарезервированный для знака или значения; в случае же преобразования с помощью функции Str начальный пробел сохранится.

При форматировании нелокализованных числовых строк, следует использовать определяемый пользователем числовой формат, чтобы обеспечить получение желаемых результатов.

Если свойству Calendar присвоено значение Gregorian и format задает форматирование даты, выдаваемым expression должно быть Gregorian . Если свойство Календарь Visual Basic имеет Hijri значение , предоставленное выражение должно иметь значение Hijri .

Если используется григорианский календарь, значение символов выражения format не изменяется. Если используется календарь Хиджра, все символы формата даты (например, dddd, mmmm, yyyy) имеют то же значение, но применяются к календарю Хиджра. Символы формата остаются английскими; символы, отображаемые в текстовом виде (например, AM и PM), отображают строку (на английском или арабском языке), связанную с этим символом. Диапазон некоторых символов при использовании календаря Хиджра изменяется.

Символы даты

Символ Диапазон
d 1–31 (день месяца без нуля в начале)
dd 01–31 (день месяца с нулем в начале)
w 1–7 (день недели, начиная с воскресенья = 1)
ww 1–53 (неделя года без нуля в начале; неделя 1 начинается с 1 января)
m 1–12 (месяц года без нуля в начале, начиная с января = 1)
mm 01–12 (месяц года с нулем в начале, начиная с января = 01)
mmm Отображает сокращенное название месяца (в названии месяцев Хиджра нет сокращений)
mmmm Отображает полное название месяца
y 1–366 (день года)
yy 00–99 (последние две цифры года)
yyyy 100–9999 (год из трех или четырех цифр)

Символы времени

Символ Диапазон
h 0–23 (1–12 с добавлением «AM» или «PM») (час суток без нуля в начале)
hh 00–23 (01–12 с добавлением «AM» или «PM») (час суток с нулем в начале)
n 0–59 (минута часа без нуля в начале)
nn 00–59 (минута часа с нулем в начале)
m 0–59 (минута часа без нуля в начале). Только если находится после h или hh
mm 00–59 (минута часа с нулем в начале). Только если находится после h или hh
s 0–59 (секунда минуты без нуля в начале)
ss 00–59 (секунда минуты с нулем в начале)

Пример

В этом примере показываются различные варианты использования функции Format для форматирования значений с использованием как именованных форматов, так и форматов, определяемых пользователем. Отображение разделителей даты (/), времени (:) и литерала AM/PM зависит от языковых настроек системы, в среде которой выполняется код. При отображении времени и дат в среде разработки используются краткие форматы даты и времени, определяемые настройками языка для кода. При их отображении в процессе выполнения кода используются краткие форматы даты и времени языка системы, которые могут отличаться от настроек языка для кода. В этом примере подразумевается использование языка «Английский (США)». Элементы MyTime и MyDate отображаются в среде разработки с использованием текущих кратких форматов даты и времени языка системы.

Различные форматы для различных числовых значений

В определяемом пользователем expression формата для чисел может иметься от одного до четырех разделов, отделяемых друг от друга точками с запятой. Если аргумент формата содержит один из именованных числовых форматов, допускается использование только одного раздела.

Если используется Результат
Только один раздел Выражение формата применяется ко всем значениям.
Два раздела Первый раздел применяется к положительным значениям и нулям, второй — к отрицательным значениям.
Три раздела Первый раздел применяется к положительным значениям, второй — к отрицательным значениям, третий — к нулям.
Четыре раздела Первый раздел применяется к положительным значениям, второй — к отрицательным значениям, третий — к нулям, четвертый — к значениям Null.

Если записать знаки точки с запятой без кода между ними, то отсутствующий раздел будет печататься с использованием формата положительного значения. Например, следующий формат отображает положительные и отрицательные значения с использованием формата первого раздела и отображает «Zero», если значением является нуль.

Различные форматы для различных строковых значений

В expression формата для строк может иметься один раздел или два раздела, отделяемых друг от друга точками с запятой (;).

Если используется Результат
Только один раздел Формат применяется ко всем строковым данным.
Два раздела Первый раздел применяется к строковым данным, второй — к значениям Null и пустым строкам («»).

Именованные форматы даты и времени

В следующей таблице указываются предопределенные имена форматов даты и времени.

Имя формата Описание
General Date Отображение даты и/или времени, например 4/3/93 05:34 PM. Если дробная часть отсутствует, отображается только дата, например 4/3/93. Если отсутствует целая часть, отображается только время, например 05:34 PM. Отображение даты определяется параметрами системы.
Long Date Отображение даты в соответствии с длинным форматом даты, используемым в системе.
Medium Date Отображение даты с использованием среднего формата даты, соответствующего языковой версии ведущего приложения.
Short Date Отображение даты в соответствии с кратким форматом даты, используемым в системе.
Long Time Отображение времени в соответствии с длинным форматом даты, используемым в системе; включает часы, минуты и секунды.
Medium Time Отображение времени в 12-часовом формате с использованием часов, минут и указателя AM/PM.
Short Time Отображение времени в 24-часовом формате, например 17:45.

Именованные числовые форматы

В следующей таблице указываются предопределенные имена числовых форматов.

Имя формата Описание
General Number Отображение числа без знака разделителя групп разрядов.
Currency Отображение числа с использованием разделителя групп разрядов, если это необходимо; отображаются две цифры справа от разделителя целой и дробной части. Вывод основывается на языковых настройках системы.
Fixed Отображение по крайней мере одной цифры слева и двух цифр справа от разделителя целой и дробной части.
Standard Отображение числа с использованием разделителя групп разрядов; отображаются по крайней мере одна цифра слева и две цифры справа от разделителя целой и дробной части.
Percent Отображение числа, умноженного на 100 со знаком процента (%), добавляемого справа; всегда отображаются две цифры справа от разделителя целой и дробной части.
Scientific Используется стандартное экспоненциальное представление.
Yes/No Отображается «Нет», если число равняется 0; в противном случае отображается «Да».
True/False Отображается False, если число равняется 0; в противном случае отображается True.
On/Off Отображается «Вкл», если число равняется 0; в противном случае отображается «Выкл».

Определяемые пользователем строковые форматы

Используйте любой из следующих знаков для создания expression формата для строк.

Знак Описание
@ Заполнитель для символов. Отображает знак или пробел. Если в строке имеется знак на позиции, в которой в строке форматирования располагается at-символ (@), отображается этот знак; в противном случае на этой позиции отображается пробел. Заполнители заполняются справа налево, если только в строке форматирования не будет представлен восклицательный знак (!).
& Заполнитель для символов. Отображает знак или ничего не отображает. Если в строке имеется знак на позиции, в которой располагается амперсанд (&), отображается этот знак; в противном случае не отображается ничего. Заполнители заполняются справа налево, если только в строке форматирования не будет представлен восклицательный знак (!).
Принудительное отображение верхнего регистра. Отображение всех знаков в формате верхнего регистра.
! Принудительное заполнение заполнителей в порядке слева направо. По умолчанию заполнители заполняются справа налево.

Определяемые пользователем форматы даты и времени

В следующей таблице указываются знаки, которые могут использоваться при создании определяемых пользователем форматов даты и времени.

Знак Описание
(:) Разделитель компонентов времени. В некоторых языковых стандартах могут использоваться другие знаки для представления разделителя компонентов времени. Этот разделитель отделяет часы, минуты и секунды, когда значения времени форматируются. Символ, используемый в качестве разделителя компонентов времени в отформатированных выходных данных, определяется параметрами системы.
(/) Разделитель компонентов даты. В некоторых языковых стандартах могут использоваться другие знаки для представления разделителя компонентов даты. Этот разделитель отделяет день, месяц и год, когда значения даты форматируются. Символ, используемый в качестве разделителя компонентов даты в отформатированных выходных данных, определяется параметрами системы.
c Отображение даты в формате ddddd и отображение времени в формате ttttt (в этом порядке). Отображение только информации о дате, если отсутствует дробная часть в дате, представленной числом; отображение только информации о времени, если отсутствует целая часть.
d Отображение дня в виде числа без нуля в начале (1–31).
dd Отображение дня в виде числа с нулем в начале (01–31).
ddd Отображение дня в виде сокращения (вс–сб). Локализовано.
dddd Отображение дня в виде полного имени (с воскресенья по субботу). Локализовано.
ddddd Отображение даты с использованием полного формата (включая день, месяц и год), соответствующего краткому формату даты в настройках системы. Кратким форматом даты по умолчанию является m/d/yy .
dddddd Отображение числа, представляющего дату, с использованием полного формата (включая день, месяц и год), соответствующего длинному формату даты в настройках системы. Длинным форматом даты по умолчанию является mmmm dd, yyyy .
w Отображение дня недели в виде числа (от 1 для воскресенья и до 7 для субботы).
ww Отображает неделю года в виде числа (1–54).
m Отображение месяца в виде числа без начального нуля (1–12). Если m следует сразу же после h или hh , отображаться будет не месяц, а минута.
mm Отображение месяца в виде числа с нулем в начале (01–12). Если m следует сразу же после h или hh , отображаться будет не месяц, а минута.
mmm Отображение месяца в виде сокращения (январь–декабрь). Локализовано.
mmmm Отображение месяца в виде полного названия месяца (январь–декабрь). Локализовано.
q Отображение квартала года в виде числа (1–4).
y Отображение дня года в виде числа (1–366).
yy Отображение года в виде двухзначного числа (00–99).
yyyy Отображение года в виде 4-значного числа (100–9999).
h Отображение часа в виде числа без нуля в начале (0–23).
hh Отображение часа в виде числа с нулем в начале (00–23).
n Отображает минуту в виде числа без начального нуля (0–59).
nn Отображает минуту в виде числа с нулем в начале (00–59).
s Отображение второго в виде числа без нуля в начале (0–59).
ss Отображение второго в виде числа с нулем в начале (00–59).
ttttt Отображение времени в полном формате (включая час, минуту и секунду) с использованием разделителя компонентов времени, определенного в формате времени, указанного в настройках системы. Начальный нуль отображается, если выбран параметр «Ноль в начале» и время до 10:00 или вечера Формат времени по умолчанию — h:mm:ss .
AM/PM Используется 12-часовой формат и отображается указатель AM в верхнем регистре с любым часом до полудня; отображается указатель PM в верхнем регистре с любым часом между полуднем и 11:59 P.M.
am/pm Используется 12-часовом формат и отображается указатель AM в нижнем регистре с любым часом до полудня; отображается указатель PM в нижнем регистре с любым часом между полуднем и 11:59 P.M.
A/P Используется 12-часовом формат и отображается указатель A в верхнем регистре с любым часом до полудня; отображается указатель P в верхнем регистре с любым часом между полуднем и 11:59 P.M.
a/p Используется 12-часовом формат и отображается указатель A в нижнем регистре с любым часом до полудня; отображается указатель P в нижнем регистре с любым часом между полуднем и 11:59 P.M.
AMPM Используйте 12-часовые часы и отображайте строковый литерал AM, как определено в вашей системе, с любым часом до полудня; отображение строкового литерала PM в соответствии с определением вашей системы с любым часом между полуднем и 23:59 AM AMPM может быть либо прописным, либо строчным, но регистр отображаемой строки соответствует строке, определенной параметрами системы. Форматом по умолчанию является AM/PM. Если вашей системе установлен 24-часовой формат, эта строка обычно устанавливается пустой.

Определяемые пользователем числовые форматы

В следующей таблице указываются знаки, которые могут использоваться при создании определяемых пользователем форматов чисел.

Знак Описание
Нет Отображение числа без форматирования.
(0) Заполнитель цифры. Отображает цифру или нуль. Если в expression имеется цифра на позиции в строке форматирования, где стоит 0, отображается эта цифра; в противном случае на этой позиции отображается нуль. Если число имеет меньше цифр, чем нулей (по любую сторону от десятичного разделителя) в выражении формата, отображаются нули в начале или в конце. Если число имеет больше цифр, чем нулей справа от разделителя целой и дробной части в выражении формата, число округляется, чтобы число десятичных разрядов соответствовало количеству нулей. Если число имеет больше цифр, чем нулей слева от разделителя целой и дробной части в выражении формата, отображается дополнительное количество цифр без изменения.
(#) Заполнитель цифры. Отображает цифру или ничего не отображает. Если в выражении имеется цифра на позиции в строке форматирования, где стоит #, отображается эта цифра; в противном случае на этой позиции отображается нуль. Этот символ работает, как заполнитель цифры 0, за исключением того, что нули в начале и в конце не отображаются, если в числе имеется столько же или меньше знаков # по любую сторону от разделителя целой и дробной части в выражении формата.
(.) Заполнитель десятичного разделителя. В некоторых языковых стандартах в качестве разделителя целой и дробной части используется запятая. Заполнитель десятичного разделителя определяет, сколько цифр отображается слева и справа от разделителя целой и дробной части. Если выражение формата содержит только знаки числа слева от этого символа, то числа меньше 1 начинаются с разделителя целой и дробной части. Чтобы отобразить нуль в начале дробного числа, используйте 0 в качестве заполнителя первой цифры слева от разделителя целой и дробной части. Фактический знак, используемый в качестве заполнителя десятичного разделителя в форматированном выводе значений, зависит от параметра «Числовой формат», заданного в вашей системе.
(%) Заполнитель процента. Выражение умножается на 100. Знак процента (%) вставляется на позиции, на которой он указан в строке формата.
(,) Разделитель групп разрядов. В некоторых языковых стандартах в качестве разделителя групп разрядов используется пробел. Разделитель групп разрядов отделяет тысячи от сотен внутри числа, в котором имеется четыре или более цифр слева от разделителя целой и дробной части. Стандарт использования разделителя групп разрядов указывается, если формат содержит разделитель групп разрядов в окружении заполнителей цифр (0 или #). Две смежные тысячи разделителей или тысяча разделителей непосредственно слева от десятичного разделителя (независимо от того, указана ли десятичная дробь) означает «масштаб числа, разделив его на 1000, округляя по мере необходимости». Например, можно использовать строку формата «##0», чтобы представить 100 миллионов как 100. Числа меньше 1 миллиона отображаются тогда как 0. Два последовательных разделителя групп разрядов, расположенные на любой позиции, но не непосредственно слева от разделителя целой и дробной части, просто указывают на использование разделителя групп разрядов. Фактический знак, используемый в качестве разделителя групп разрядов в форматированном выводе значений, зависит от параметра «Числовой формат», заданного в вашей системе.
(:) Разделитель компонентов времени. В некоторых языковых стандартах могут использоваться другие знаки для представления разделителя компонентов времени. Этот разделитель отделяет часы, минуты и секунды, когда значения времени форматируются. Символ, используемый в качестве разделителя компонентов времени в отформатированных выходных данных, определяется параметрами системы.
(/) Разделитель компонентов даты. В некоторых языковых стандартах могут использоваться другие знаки для представления разделителя компонентов даты. Этот разделитель отделяет день, месяц и год, когда значения даты форматируются. Символ, используемый в качестве разделителя компонентов даты в отформатированных выходных данных, определяется параметрами системы.
(E- E+ e- e+) Экспоненциальный формат. Если выражение формата содержит по крайней мере один заполнитель цифры (0 или #) справа от E-, E+, e- или e+, данное число отображается в экспоненциальном формате и между числом и его показателем степени вставляется знак E или e. Количество заполнителей цифр справа определяет число цифр в показателе степени. Используйте знаки E- или e-, чтобы поместить знак минуса рядом с отрицательными показателями степени. Используйте знаки E+ или e+, чтобы поместить знак плюса рядом с положительными показателями степени.
— + $ ( ) Отображение знака литерала. Чтобы отобразить знак, отличный от указанных здесь, запишите перед ним знак обратной косой черты ( ) или заключите его в двойные кавычки (» «).
() Отображение знака, стоящего после него в строке формата. Чтобы отобразить какой-либо знак, имеющий специальное значение, как знак литерала, запишите перед ним знак обратной косой черты ( ). Сам знак обратной косой черты при этом не отображается. Использование знака обратной косой черты аналогично по своему действию заключению соответствующего знака в двойные кавычки. Чтобы отобразить обратную косую черту, необходимо записать два таких знака ( \ ). Примерами знаков, которые не могут быть отображены как знаки литералов, являются знаки форматирования даты и времени (a, c, d, h, m, n, p, q, s, t, w, y, / и :), знаки форматирования чисел (#, 0, %, E, e, запятая и точка) и знаки форматирования строк (@, &, и !).
(«ABC») Отображение строки в двойных кавычках (» «). Чтобы включить строку в format непосредственно из кода, необходимо использовать Chr(34), чтобы заключить текст (34 — это код знака для знака кавычки («)).

См. также

Поддержка и обратная связь

Есть вопросы или отзывы, касающиеся Office VBA или этой статьи? Руководство по другим способам получения поддержки и отправки отзывов см. в статье Поддержка Office VBA и обратная связь.

Источник

Понравилась статья? Поделить с друзьями:
  • Format track changes word
  • Formatting text from pdf in word
  • Format times in excel
  • Formatting text fields in word
  • Format the word document