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

In this Article

  • Formatting Numbers in Excel VBA
  • How to Use the Format Function in VBA
    • Creating a Format String
    • Using a Format String for Alignment
    • Using Literal Characters Within the Format String
    • Use of Commas in a Format String
    • Creating Conditional Formatting within the Format String
    • Using Fractions in Formatting Strings
    • Date and Time Formats
    • Predefined Formats
    • General Number
    • Currency
    • Fixed
    • Standard
    • Percent
    • Scientific
    • Yes/No
    • True/False
    • On/Off
    • General Date
    • Long Date
    • Medium Date
    • Short Date
    • Long Time
    • Medium Time
    • Short Time
    • Dangers of Using Excel’s Pre-Defined Formats in Dates and Times
    • User-Defined Formats for Numbers
    • User-Defined Formats for Dates and Times

Formatting Numbers in Excel VBA

Numbers come in all kinds of formats in Excel worksheets. You may already be familiar with the pop-up window in Excel for making use of different numerical formats:

PIC 01

Formatting of numbers make the numbers easier to read and understand. The Excel default for numbers entered into cells is ‘General’ format, which means that the number is displayed exactly as you typed it in.

For example, if you enter a round number e.g. 4238, it will be displayed as 4238 with no decimal point or thousands separators. A decimal number such as 9325.89 will be displayed with the decimal point and the decimals. This means that it will not line up in the column with the round numbers, and will look extremely messy.

Also, without showing the thousands separators, it is difficult to see how large a number actually is without counting the individual digits.  Is it in millions or tens of millions?

From the point of view of a user looking down a column of numbers, this makes it quite difficult to read and compare.

PIC 02

In VBA you have access to exactly the same range of formats that you have on the front end of Excel. This applies to not only an entered value in a cell on a worksheet, but also things like message boxes, UserForm controls, charts and graphs, and the Excel status bar at the bottom left hand corner of the worksheet.

The Format function is an extremely useful function in VBA in presentation terms, but it is also very complex in terms of the flexibility offered in how numbers are displayed.

How to Use the Format Function in VBA

If you are showing a message box, then the Format function can be used directly:

MsgBox Format(1234567.89, "#,##0.00")

This will display a large number using commas to separate the thousands and to show 2 decimal places.  The result will be 1,234,567.89.  The zeros in place of the hash ensure that decimals will be shown as 00 in whole numbers, and that there is a leading zero for a number which is less than 1

The hashtag symbol (#) represents a digit placeholder which displays a digit if it is available in that position, or else nothing.

You can also use the format function to address an individual cell, or a range of cells to change the format:

Sheets("Sheet1").Range("A1:A10").NumberFormat = "#,##0.00"

This code will set the range of cells (A1 to A10) to a custom format which separates the thousands with commas and shows 2 decimal places.

If you check the format of the cells on the Excel front end, you will find that a new custom format has been created.

You can also format numbers on the Excel Status Bar at the bottom left hand corner of the Excel window:

Application.StatusBar = Format(1234567.89, "#,##0.00")

PIC 03

You clear this from the status bar by using:

Application.StatusBar = ""

Creating a Format String

This example will add the text ‘Total Sales’ after each number, as well as including a thousands separator

Sheets("Sheet1").Range("A1:A6").NumberFormat = "#,##0.00"" Total Sales"""

This is what your numbers will look like:

PIC 04

Note that cell A6 has a ‘SUM’ formula, and this will include the ‘Total Sales’ text without requiring formatting.  If the formatting is applied, as in the above code, it will not put an extra instance of ‘Total Sales’ into cell A6

Although the cells now display alpha numeric characters, the numbers are still present in numeric form. The ‘SUM’ formula still works because it is using the numeric value in the background, not how the number is formatted.

The comma in the format string provides the thousands separator. Note that you only need to put this in the string once.  If the number runs into millions or billions, it will still separate the digits into groups of 3

The zero in the format string (0) is a digit placeholder. It displays a digit if it is there, or a zero. Its positioning is very important to ensure uniformity with the formatting

In the format string, the hash characters (#) will display nothing if there is no digit.  However, if there is a number like .8 (all decimals), we want it to show as 0.80 so that it lines up with the other numbers.

By using a single zero to the left of the decimal point and two zeros to the right of the decimal point in the format string, this will give the required result (0.80).

If there was only one zero to the right of the decimal point, then the result would be ‘0.8’ and everything would be displayed to one decimal place.

Using a Format String for Alignment

We may want to see all the decimal numbers in a range aligned on their decimal points, so that all the decimal points are directly under each other, however many places of decimals there are on each number.

You can use a question mark (?) within your format string to do this.  The ‘?’ indicates that a number is shown if it is available, or a space

Sheets("Sheet1").Range("A1:A6").NumberFormat = "#,##0.00??"

This will display your numbers as follows:

PIC 05

All the decimal points now line up underneath each other.  Cell A5 has three decimal places and this would throw the alignment out normally, but using the ‘?’ character aligns everything perfectly.

Using Literal Characters Within the Format String

You can add any literal character into your format string by preceding it with a backslash ().

Suppose that you want to show a particular currency indicator for your numbers which is not based on your locale.  The problem is that if you use a currency indicator, Excel automatically refers to your local and changes it to the one appropriate for the locale that is set on the Windows Control Panel.  This could have implications if your Excel application is being distributed in other countries and you want to ensure that whatever the locale is, the currency indicator is always the same.

You may also want to indicate that the numbers are in millions in the following example:

Sheets("Sheet1").Range("A1:A6").NumberFormat = "$#,##0.00 m"

This will produce the following results on your worksheet:

PIC 06

In using a backslash to display literal characters, you do not need to use a backslash for each individual character within a string. You can use:

Sheets("Sheet1").Range("A1:A6").NumberFormat = "$#,##0.00 mill"

This will display ‘mill’ after every number within the formatted range.

You can use most characters as literals, but not reserved characters such as 0, #,?

Use of Commas in a Format String

We have already seen that commas can be used to create thousands separators for large numbers, but they can also be used in another way.

By using them at the end of the numeric part of the format string, they act as scalers of thousands. In other words, they will divide each number by 1,000 every time there is a comma.

In the example data, we are showing it with an indicator that it is in millions. By inserting one comma into the format string, we can show those numbers divided by 1,000.

Sheets("Sheet1").Range("A1:A6").NumberFormat = "$#,##0.00,m"

This will show the numbers divided by 1,000 although the original number will still be in background in the cell.

If you put two commas in the format string, then the numbers will be divided by a million

Sheets("Sheet1").Range("A1:A6").NumberFormat = "$#,##0.00,,m"

This will be the result using only one comma (divide by 1,000):

PIC 07

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

Creating Conditional Formatting within the Format String

You could set up conditional formatting on the front end of Excel, but you can also do it within your VBA code, which means that you can manipulate the format string programmatically to make changes.

You can use up to four sections within your format string.  Each section is delimited by a semicolon (;). The four sections correspond to positive, negative, zero, and text

Range("A1:A7").NumberFormat = "#,##0.00;[Red]-#,##0.00;[Green] #,##0.00;[Blue]”

In this example, we use the same hash, comma, and zero characters to provide thousand separators and two decimal points, but we now have different sections for each type of value.

The first section is for positive numbers and is no different to what we have already seen previously in terms of format.

The second section for negative numbers introduces a color (Red) which is held within a pair of square brackets. The format is the same as for positive numbers except that a minus (-) sign has been added in front.

The third section for zero numbers uses a color (Green) within square brackets with the numeric string the same as for positive numbers.

The final section is for text values, and all that this needs is a color (Blue) again within square brackets

This is the result of applying this format string:

PIC 08

You can go further with conditions within the format string.  Suppose that you wanted to show every positive number above 10,000 as green, and every other number as red you could use this format string:

Range("A1:A7").NumberFormat = "[>=10000][Green]#,##0.00;[<10000][Red]#,##0.00"

This format string includes conditions for >=10000 set in square brackets so that green will only be used where the number is greater than or equal to 10000

This is the result:

PIC 09

Using Fractions in Formatting Strings

Fractions are not often used in spreadsheets, since they normally equate to decimals which everyone is familiar with.

However, sometimes they do serve a purpose. This example will display dollars and cents:

Range("A1:A7").NumberFormat = "#,##0 "" dollars and "" 00/100 ""  cents """

This is the result that will be produced:

PIC 10

Remember that in spite of the numbers being displayed as text, they are still there in the background as numbers and all the Excel formulas can still be used on them.

Date and Time Formats

Dates are actually numbers and you can use formats on them in the same way as for numbers.  If you format a date as a numeric number, you will see a large number to the left of the decimal point and a number of decimal places. The number to the left of the decimal point shows the number of days starting at 01-Jan-1900, and the decimal places show the time based on 24hrs

MsgBox Format(Now(), "dd-mmm-yyyy")

This will format the current date to show ’08-Jul-2020’. Using ‘mmm’ for the month displays the first three characters of the month name.  If you want the full month name then you use ‘mmmm’

You can include times in your format string:

MsgBox Format(Now(), "dd-mmm-yyyy hh:mm AM/PM")

This will display ’08-Jul-2020 01:25 PM’

‘hh:mm’ represents hours and minutes and AM/PM uses a 12-hour clock as opposed to a 24-hour clock.

You can incorporate text characters into your format string:

MsgBox Format(Now(), "dd-mmm-yyyy hh:mm AM/PM"" today""")

This will display ’08-Jul-2020 01:25 PM today’

You can also use literal characters using a backslash in front in the same way as for numeric format strings.

VBA Programming | Code Generator does work for you!

Predefined Formats

Excel has a number of built-in formats for both numbers and dates that you can use in your code.  These mainly reflect what is available on the number formatting front end, although some of them go beyond what is normally available on the pop-up window.  Also, you do not have the flexibility over number of decimal places, or whether thousands separators are used.

General Number

This format will display the number exactly as it is

MsgBox Format(1234567.89, "General Number")

The result will be 1234567.89

Currency

MsgBox Format(1234567.894, "Currency")

This format will add a currency symbol in front of the number e.g. $, £ depending on your locale, but it will also format the number to 2 decimal places and will separate the thousands with commas.

The result will be $1,234,567.89

Fixed

MsgBox Format(1234567.894, "Fixed")

This format displays at least one digit to the left but only two digits to the right of the decimal point.

The result will be 1234567.89

Standard

MsgBox Format(1234567.894, "Standard")

This displays the number with the thousand separators, but only to two decimal places.

The result will be 1,234,567.89

AutoMacro | Ultimate VBA Add-in | Click for Free Trial!

Percent

MsgBox Format(1234567.894, "Percent")

The number is multiplied by 100 and a percentage symbol (%) is added at the end of the number.  The format displays to 2 decimal places

The result will be 123456789.40%

Scientific

MsgBox Format(1234567.894, "Scientific")

This converts the number to Exponential format

The result will be 1.23E+06

Yes/No

MsgBox Format(1234567.894, "Yes/No")

This displays ‘No’ if the number is zero, otherwise displays ‘Yes’

The result will be ‘Yes’

True/False

MsgBox Format(1234567.894, "True/False")

This displays ‘False’ if the number is zero, otherwise displays ‘True’

The result will be ‘True’

AutoMacro | Ultimate VBA Add-in | Click for Free Trial!

On/Off

MsgBox Format(1234567.894, "On/Off")

This displays ‘Off’ if the number is zero, otherwise displays ‘On’

The result will be ‘On’

General Date

MsgBox Format(Now(), "General Date")

This will display the date as date and time using AM/PM notation.  How the date is displayed depends on your settings in the Windows Control Panel (Clock and Region | Region). It may be displayed as ‘mm/dd/yyyy’ or ‘dd/mm/yyyy’

The result will be ‘7/7/2020 3:48:25 PM’

Long Date

MsgBox Format(Now(), "Long Date")

This will display a long date as defined in the Windows Control Panel (Clock and Region | Region).  Note that it does not include the time.

The result will be ‘Tuesday, July 7, 2020’

Medium Date

MsgBox Format(Now(), "Medium Date")

This displays a date as defined in the short date settings as defined by locale in the Windows Control Panel.

The result will be ’07-Jul-20’

AutoMacro | Ultimate VBA Add-in | Click for Free Trial!

Short Date

MsgBox Format(Now(), "Short Date")

Displays a short date as defined in the Windows Control Panel (Clock and Region | Region). How the date is displayed depends on your locale. It may be displayed as ‘mm/dd/yyyy’ or ‘dd/mm/yyyy’

The result will be ‘7/7/2020’

Long Time

MsgBox Format(Now(), "Long Time")

Displays a long time as defined in Windows Control Panel (Clock and Region | Region).

The result will be ‘4:11:39 PM’

Medium Time

MsgBox Format(Now(), "Medium Time")

Displays a medium time as defined by your locale in the Windows Control Panel. This is usually set as 12-hour format using hours, minutes, and seconds and the AM/PM format.

The result will be ’04:15 PM’

Short Time

MsgBox Format(Now(), "Short Time")

Displays a medium time as defined in Windows Control Panel (Clock and Region | Region). This is usually set as 24-hour format with hours and minutes

The result will be ’16:18’

AutoMacro | Ultimate VBA Add-in | Click for Free Trial!

Dangers of Using Excel’s Pre-Defined Formats in Dates and Times

The use of the pre-defined formats for dates and times in Excel VBA is very dependent on the settings in the Windows Control Panel and also what the locale is set to

Users can easily alter these settings, and this will have an effect on how your dates and times are displayed in Excel

For example, if you develop an Excel application which uses pre-defined formats within your VBA code, these may change completely if a user is in a different country or using a different locale to you.  You may find that column widths do not fit the date definition, or on a user form the Active X control such as a combo box (drop down) control is too narrow for the dates and times to be displayed properly.

You need to consider where the audience is geographically when you develop your Excel application

User-Defined Formats for Numbers

There are a number of different parameters that you can use when defining your format string:

Character Description
Null String No formatting
0 Digit placeholder. Displays a digit or a zero. If there is a digit for that position then it displays the digit otherwise it displays 0. If there are fewer digits than zeros, then you will get leading or trailing zeros. If there are more digits after the decimal point than there are zeros, then the number is rounded to the number of decimal places shown by the zeros. If there are more digits before the decimal point than zeros these will be displayed normally.
# Digit placeholder. This displays a digit or nothing. It works the same as the zero placeholder above, except that leading and trailing zeros are not displayed. For example 0.75 would be displayed using zero placeholders, but this would be .75 using # placeholders.
. Decimal point. Only one permitted per format string. This character depends on the settings in the Windows Control Panel.
% Percentage placeholder. Multiplies number by 100 and places % character where it appears in the format string
, (comma) Thousand separator. This is used if 0 or # placeholders are used and the format string contains a comma. One comma to the left of the decimal point indicates round to the nearest thousand. E.g. ##0, Two adjacent commas to the left of the thousand separator indicate rounding to the nearest million. E.g. ##0,,
E- E+ Scientific format. This displays the number exponentially.
: (colon) Time separator – used when formatting a time to split hours, minutes and seconds.
/ Date separator – this is used when specifying a format for a date
– + £ $ ( ) Displays a literal character. To display a character other than listed here, precede it with a backslash ()

User-Defined Formats for Dates and Times

These characters can all be used in you format string when formatting dates and times:

Character Meaning
c Displays the date as ddddd and the time as ttttt
d Display the day as a number without leading zero
dd Display the day as a number with leading zero
ddd Display the day as an abbreviation (Sun – Sat)
dddd Display the full name of the day (Sunday – Saturday)
ddddd Display a date serial number as a complete date according to Short Date in the International settings of the windows Control Panel
dddddd Displays a date serial number as a complete date according to Long Date in the International settings of the Windows Control Panel.
w Displays the day of the week as a number (1 = Sunday)
ww Displays the week of the year as a number (1-53)
m Displays the month as a number without leading zero
mm Displays the month as a number with leading zeros
mmm Displays month as an abbreviation (Jan-Dec)
mmmm Displays the full name of the month (January – December)
q Displays the quarter of the year as a number (1-4)
y Displays the day of the year as a number (1-366)
yy Displays the year as a two-digit number
yyyy Displays the year as four-digit number
h Displays the hour as a number without leading zero
hh Displays the hour as a number with leading zero
n Displays the minute as a number without leading zero
nn Displays the minute as a number with leading zero
s Displays the second as a number without leading zero
ss Displays the second as a number with leading zero
ttttt Display a time serial number as a complete time.
AM/PM Use a 12-hour clock and display AM or PM to indicate before or after noon.
am/pm Use a 12-hour clock and use am or pm to indicate before or after noon
A/P Use a 12-hour clock and use A or P to indicate before or after noon
a/p Use a 12-hour clock and use a or p to indicate before or after noon
 

Dophin

Пользователь

Сообщений: 2684
Регистрация: 01.01.1970

нашел вот такой код от ZVI  

  все работает, (правда не знаю как)  

  Единственно хотелось бы чтобы  формат данных в текстбоксе был # ##0р  

    код от ZVI  

  ‘Ввод в TextBox только чисел в заданном диапазоне  
‘с заданным десятичным разделителем (нажимать можно и точку и запятую)  
‘с ограничением количества десятичных разрядов  
Private Sub TextBox1_Change()  
Const MIN = 0 ‘ минимальное значение  
Const MAX = 100000000 ‘ максимальное значение  
Const DECSEP = «.» ‘ дес. разделитель: запятая или точка  
Const DECPLACES = 2 ‘ количество дес. разрядов  
Dim i As Double, j As Integer, ds As String, s As String  
Static old As String  
If DECSEP = «.» Then ds = «,» Else ds = «.»  
On Error Resume Next  
s = TextBox1  
If Len(s) = 0 Then old = «»: Exit Sub  
s = Replace(Replace(s, » «, «»), ds, DECSEP)  
TextBox1 = s  
i = CDbl(Replace(s, DECSEP, Mid$(CStr(1.2), 2, 1)))  
j = InStr(s, DECSEP)  
If j > 0 Then j = Len(s) — j  
If err <> 0 Or i < MIN Or i > MAX Or j > DECPLACES Then  
TextBox1 = old  
Else  
old = TextBox1  
End If  
OKButton.Enabled = True  
End Sub

 

Юрий М

Модератор

Сообщений: 60575
Регистрация: 14.09.2012

Контакты см. в профиле

В общем случае это будет выглядеть так:  
TextBox1 = Format(TextBox1, «Здесь_Ваш_Формат»)  
Попробуйте так:  
TextBox1.Value = Format(TextBox1.Value, «#,##0») & «р»

 

Dophin

Пользователь

Сообщений: 2684
Регистрация: 01.01.1970

так в ячейке получается текст «5 000р.»,    

  надо чтобы в ячейке было число, а формат ячейки — был денежный

 

Dophin

Пользователь

Сообщений: 2684
Регистрация: 01.01.1970

вопрос пока снят. Сделал так:  

     Cells(lLastRow + 1, 5).Value = Сумма.Value  
   Cells(lLastRow + 1, 5).NumberFormat = «#,##0$»

 

Dophin

Пользователь

Сообщений: 2684
Регистрация: 01.01.1970

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

  Куда воткнуть TextBox1 = Format(TextBox1, «Здесь_Ваш_Формат») применительно к полю Сумма не понял, поэтому решил пока отложить.  

  Если покажете как — буду признателен)

 

ytk5kyky

Пользователь

Сообщений: 2410
Регистрация: 01.01.1970

Я воткнул на событие Сумма_Exit  
И надо было Dim old As String добавить

 

VovaK

Пользователь

Сообщений: 1716
Регистрация: 01.01.1970

#7

24.12.2009 13:01:20

Лузер, я тоже так пытался — только время потерял (я про Format(Сумма, «#,##0 $»)), у меня почему то он не работает как хотелось бы.    

  Dophin если Вам достаточно доллара в конце, то смотри пример. Если желаете регулирование числа разрядов в конце. Маякните покажу — это не сложно.      

  Касательно кода — уводит кирилица, рекомендую отвыкнуть не привыкая. На это две причины — необходимость переключения раскладки при написании кода, и может кривить на английских локализациях.    

  В целом молодцом при условии, что все понятно…

Прикрепленные файлы

  • post_86625.xls (71 КБ)

I’m trying to create a custom format such that the number will be displayed with commas as the thousands separator. Where I am struggling to find a solution (both through trial and error as well as searching) with a decimal point if the number has one, but without a decimal point if the number is whole.

Here’s what I would like to achieve:
— «123» displays as «123»
— «1234» displays as «1,234»
— «1234.5» displays as «1,234.5»
— «1234.56» displays as «1,234.56»
— «1234.567» displays as «1,234.57»

Here’s what I have tried so far, to no avail:

Print Format(1234, "Standard") 'Displays "1,234.00"
Print Format(1234, "#,###.##") 'Displays "1,234."

These are not the desired results, as it unnecessarily displays the decimal. How can I access the decimal point when needed, and avoid when not, all while having the thousands separator?


.NET Framework (current version)

 

Опубликовано: Октябрь 2016

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

Пространство имен:

 
Microsoft.VisualBasic
Сборка:
 Microsoft.VisualBasic (в Microsoft.VisualBasic.dll)

Public Shared Function Format (

Expression As Object,

Style As String

) As String

Параметры

Expression
Type:
System.Object

Обязательный. Любое допустимое выражение.

Style
Type:
System.String

Необязательно. Недопустимый формат именованный или определенный пользователем String выражение.

Возвращаемое значение

Type:
System.String

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


String.Format Метод также предоставляет аналогичные функциональные возможности.

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

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

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

Если вы используете

Это результат

Только одна секция

Выражение форматирования применяется ко всем значениям.

Две секции

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

Три секции

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

Следующий
пример имеет две секции: первая определяет формат для положительных
значений и нулей; Во втором разделе определяет формат для отрицательных
значений.
Поскольку Style аргумент Format функция принимает строку, она заключена в кавычки.

Dim Style1 As String = «$#,##0;($#,##0)»

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

Dim Style2 As String = «$#,##0;;Zero»

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

Имя формата

Описание


General Number, G или g

Отображает число без разделителя групп разрядов.

Например Format(&H3FA, «g») возвращает 1018.


Currency, C или c

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

Например Format(1234567, «c») возвращает $1,234,567.00.


Fixed, F или f

Отображает хотя бы одну цифру слева и две цифры справа от десятичного разделителя.

Например Format(1234567, «f») возвращает 1234567.00.


Standard, N или n

Отображает число с разделителя групп разрядов, хотя бы одну цифру слева и две цифры справа от десятичного разделителя.

Например Format(1234567, «n») возвращает 1,234,567.00.

Percent

Отображает
число, умноженное на 100, со знаком процента (%), стоящим
непосредственно справа, всегда отображает две цифры справа от
десятичного разделителя.

Например Format(0.4744, «Percent») возвращает 47.44%.


P, или p

Отображает
число с разделителем тысячи, умноженное на 100, со знаком процента (%),
стоящим справа и отделенным от одного пробела, всегда отображает две
цифры справа от десятичного разделителя.

Например Format(0.80345, «p») возвращает 80.35 %.

Scientific

Использует стандартное экспоненциальное представление чисел с указанием двух значащих цифр.

Например Format(1234567, «Scientific») возвращает 1.23E+06.


E, или e

Использует стандартное экспоненциальное представление чисел, предоставляя шесть значащих цифр.

Например Format(1234567, «e») возвращает 1.234567e+006.


D, или d

Отображает номер строки, содержащей значение числа в десятичном (на основе 10) формате. Этот параметр поддерживается для целых типов (Byte, Short, Integer, Long) только.

Например Format(&H7F, «d») возвращает 127.


X, или x

Отображает номер строки, содержащей значение числа в шестнадцатеричном (на основе 16) формате. Этот параметр поддерживается для целых типов (Byte, Short, Integer, Long) только.

Например Format(127, «x») возвращает 7f.

Yes/No

Отображает No Если число равно 0; в противном случае, Yes.

Например Format(0, «Yes/No») возвращает No.

True/False

Отображает False Если число равно 0; в противном случае, True.

Например Format(1, «True/False») возвращает True.

On/Off

Отображает Off Если число равно 0; в противном случае, On.

Например Format(1, «On/Off») возвращает On.


Yes/No, True/False, И On/Off форматы не поддерживаются.

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

Знак

Описание

Нет

Отображает число без форматирования.

(0)

Заполнитель цифры. Отображает цифру или ноль.
Если выражение содержит цифру в позиции, где в строке формата стоит
ноль, откройте его; в противном случае — нулю в этой позиции.

Если
количество цифр меньше, чем нулей (с обеих сторон от десятичного
разделителя) в выражении форматирования, выводится с начальными либо
конечными нулями.

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

Если число имеет больше цифр слева от десятичного разделителя, чем
нулей слева от десятичного разделителя в выражении форматирования,
лишние цифры без изменения отображаются.

(#)

Заполнитель цифры. Отображает цифру или ничего. Если выражение содержит цифру в позиции, где # в строке формата стоит знак отображается; в противном случае — ничего не выводит в этой позиции.

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

(.)

Десятичный разделитель. Определяет, сколько разрядов отображается слева и справа от десятичного разделителя. Если выражение формата содержит только # символов слева от этого символа, числа меньше 1 начинаются с десятичного разделителя.
Чтобы отобразить в дробных числах отображался начальный ноль, укажите
ноль в качестве первого цифрового заполнителя слева от десятичного
разделителя.
В некоторых региональных стандартах в качестве десятичного разделителя используется запятая.
Фактический символ, используется в качестве десятичного заполнителя в
отформатированном значении, зависит от числового формата,
распознаваемого системой.

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

(%)

Заполнитель процента. Умножает выражение на 100. Символ процента (%) вставляется в позицию, где он отображается в строке формата.

(,)

Разделитель групп разрядов. Разделитель групп разрядов отделяет тысячи от сотен в числе с четырьмя или более разрядами слева от десятичного разделителя. Указанный стандартном использовании разделителя групп разрядов Если формат содержит разделитель тысяч, заполнители цифр (0 или #).

Разделитель
групп разрядов слева от десятичного разделителя (ли указан десятичное
число) или крайним правым символов в строке, это означает
«масштабирование числа путем деления его на 1 000 округления при
необходимости.»
Числа меньше 1 000, но больше или равно 500 отображаются как 1, а числа меньше 500 отображаются как 0.
Два смежных разделителя групп разрядов в этой позиции масштабирования с
коэффициентом 1 миллион и дополнительный фактор 1 000 за каждый
дополнительный разделитель.

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

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

Например рассмотрим следующие три строки форматирования:


  • «#,0.», который использует разделитель тысяч для форматирования числа 100 миллионов в строку «100,000,000».


  • «#0,.», которая использует деление на тысячу для форматирования числа 100 миллионов в строку «100000».


  • «#,0,.», который использует разделитель тысяч и деление на тысячу для форматирования числа 100 миллионов в строку «100,000».

(:)

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

(/)

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

(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«)

Вывод строки, заключенной в двойные кавычки (» «). Чтобы включить строку в аргумент стиля из кода, необходимо использовать Chr(34) заключить текст (34 — код символа для обозначения кавычек (««)).

Следующая таблица содержит некоторые образцы выражений форматирования для чисел.
(Предполагается, что параметр языкового стандарта системы является
английский (США)) Первый столбец содержит строки форматирования для Style аргумент Format
функции; другие столбцы содержат результирующие выходные данные, если
форматируемые данные имеют значение, заданное в заголовке столбца.

Формат (Style)

формат «5»

в формате «-5»

«0,5» в формате

Zero-length string («»)

5

-5

0.5

0

5

-5

1

0.00

5.00

-5.00

0.50

#,##0

5

-5

1

$#,##0;($#,##0)

$5

($5)

$1

$#,##0.00;($#,##0.00)

$5.00

($5.00)

$0.50

0%

500%

-500%

50%

0.00%

500.00%

-500.00%

50.00%

0.00E+00

5.00E+00

-5.00E+00

5.00E-01

0.00E-00

5.00E00

-5.00E00

5.00E-01

Ниже приведены стандартные Дата и имена в формате времени. Их можно использовать по имени в качестве аргумента стиля Format функции:

Название формата

Описание


General Date, или G

Отображает дату и время. Например, 3/12/2008 11:07:31 AM. Отображение даты определяется текущее значение языка и региональных параметров приложения.


Long Date, Medium Date или D

Отображает дату в соответствии с форматом даты в текущей культуре. Например, Wednesday, March 12, 2008.


Short Date, или d

Отображает дату в формате короткой даты в текущей культуре. Например, 3/12/2008.


d Символ отображает день в формате даты, определяемой пользователем.


Long Time, Medium Time или T

Отображает время, используя текущую культуру длинный формат времени; обычно включает часы, минуты и секунды. Например, 11:07:31 AM.


Short Time или t

Отображает время, используя текущую культуру краткий формат времени. Например, 11:07 AM.


t Отображает символ AM или PM значения для языков, использующих 12-часовой формат времени, определяемого пользователем.

f

Отображает длинный формат даты и короткое время в соответствии с форматом в текущей культуре. Например, Wednesday, March 12, 2008 11:07 AM.

F

Отображает длинный формат даты и время в соответствии с форматом в текущей культуре. Например, Wednesday, March 12, 2008 11:07:31 AM.

g

Отображает краткий формат даты и короткое время в соответствии с форматом в текущей культуре. Например, 3/12/2008 11:07 AM.


M, m

Отображает месяц и день даты. Например, March 12.


M Символ отображает месяц в формате даты, определяемой пользователем.

m Символ Отображает минуты в формате времени, определяемого пользователем.


R, r

Форматирует дату в соответствии с RFC1123Pattern свойство. Например, Wed, 12 Mar 2008 11:07:31 GMT. Форматированные даты не изменяется значение даты и времени. Значение даты и времени по Гринвичу следует настроить перед вызовом метода Format функции.

s

Форматирует дату и время в виде сортируемого индекса. Например, 2008-03-12T11:07:31.


s Символ Отображает секунды в формате времени, определяемого пользователем.

u

Форматирует дату и время в виде сортируемого индекса GMT. Например, 2008-03-12 11:07:31Z.

U

Форматы даты и времени с даты и время в качестве GMT. Например, Wednesday, March 12, 2008 6:07:31 PM.


Y, y

Форматирует дату как год и месяц. Например, March, 2008.


Y И y символов отображают год в формате даты, определяемой пользователем.

Дополнительные сведения о приложения текущего языка и региональных параметров в разделе Влияние языка и региональных параметров на строки в Visual Basic .

Ниже приведены символы, которые можно использовать для создания форматов даты и времени, определяемого пользователем. В отличие от более ранних версиях Visual Basic, эти символы форматирования зависят от регистра.

Знак

Описание

(:)

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

(/)

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

(%)

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

d

Отображает день в виде числа без нуля в начале (например, 1). Используйте %d если это единственный знак в определяемых пользователем числовом формате.

dd

Отображает день в виде числа с ведущими нулями (например, 01).

ddd

Вывод сокращенного названия дня (например, Sun).

dddd

Отображает день в виде полного имени (например, Sunday).

M

Отображает месяц в виде числа без нуля в начале (например, январь отображается как 1). Используйте %M если это единственный знак в определяемых пользователем числовом формате.

MM

Отображает месяц в виде числа с нулем в начале (например, 01/12/01).

MMM

Вывод сокращенного названия месяца (например, Jan).

MMMM

Отображает полное название месяца (например, January).

gg

Отображает строку эры (например, A.D.).

h

Выводит часы в виде числа без нулей в 12-часовом формате (например, 1:15:15 PM). Используйте %h если это единственный знак в определяемых пользователем числовом формате.

hh

Выводит часы в виде числа с ведущими нулями в 12-часовом формате (например, 01:15:15 PM).

H

Выводит часы в виде числа без нулей в 24-часовом формате (например, 1:15:15). Используйте %H если это единственный знак в определяемых пользователем числовом формате.

HH

Выводит часы в виде числа с ведущими нулями в 24-часовом формате (например, 01:15:15).

m

Отображает минуты в виде числа без ведущих нулей (например, 12:1:15). Используйте %m если это единственный знак в определяемых пользователем числовом формате.

mm

Отображает минуты в виде числа с ведущими нулями (например, 12:01:15).

s

Отображает секунды как число без нулей (например, 12:15:5). Используйте %s если это единственный знак в определяемых пользователем числовом формате.

ss

Отображает секунды в виде числа с ведущими нулями (например, 12:15:05).

f

Отображает доли секунды. Например ff отображает сотые доли секунды, а ffff отображает десятитысячные доли секунды. Можно использовать до семи f символов в определяемом пользователем формате. Используйте %f если это единственный знак в определяемых пользователем числовом формате.

t

Использует 12-часовой формат и отображает A для любого часа до полудня отображает P для любого часа от полудня до 23:59. Используйте %t если это единственный знак в определяемых пользователем числовом формате.

tt

Для языков, использующих 12-часовой формат, отображает AM времени до полудня отображает PM при выводе времени с полудня до 23:59.

Для языков, использующих 24-часовом формате, ничего не выводит.

y

Отображает число года (0-9) без предшествующих нулей. Используйте %y если это единственный знак в определяемых пользователем числовом формате.

yy

Отображает год в числовом формате двух цифр с нулем в начале, если применимо.

yyy

Отображает год в числовом формате из четырех цифр.

yyyy

Отображает год в числовом формате из четырех цифр.

z

Выводит Сдвиг часового пояса без нуля в начале (например, -8). Используйте %z если это единственный знак в определяемых пользователем числовом формате.

zz

Выводит Сдвиг часового пояса с нулем в начале (например, -08)

zzz

Отображает полный Сдвиг часового пояса (например, -08:00)

Ниже приведены примеры пользовательских форматов даты и времени для December 7, 1958, 8:50 PM, 35 seconds:

Формат

Отображение

M/d/yy

12/7/58

d-MMM

7-Dec

d-MMMM-yy

7-December-58

d MMMM

7 December

MMMM yy

December 58

hh:mm tt

08:50 PM

h:mm:ss t

8:50:35 P

H:mm

20:50

H:mm:ss

20:50:35

M/d/yyyy H:mm

12/7/1958 20:50

Минимальный квант времени устройства определяется производителем устройства. Если квант времени для данного устройства достаточно грубым f символ формата возвращает 0 при запуске на этом устройстве.

В этом примере показаны различные способы использования Format функции для форматирования значений с помощью обоих String форматы и форматы, определенные пользователем. В качестве разделителя даты (/), разделитель компонентов времени (:) и индикаторов AM/PM (t и tt), Фактическое отображение системой зависит от региональных параметров, используя код. Если время и даты отображаются в среде разработки, используются краткий формат времени и даты языкового стандарта кода.

System_CAPS_noteПримечание

Для языков, использующих 24-часовом формате, индикаторы AM/PM (t и tt) не отображаются.

Dim TestDateTime As Date = #1/27/2001 5:04:23 PM#

Dim TestStr As String

‘ Returns current system time in the system-defined long time format.

TestStr = Format(Now(), «Long Time»)

‘ Returns current system date in the system-defined long date format.

TestStr = Format(Now(), «Long Date»)

‘ Also returns current system date in the system-defined long date

‘ format, using the single letter code for the format.

TestStr = Format(Now(), «D»)

‘ Returns the value of TestDateTime in user-defined date/time formats.

‘ Returns «5:4:23».

TestStr = Format(TestDateTime, «h:m:s»)

‘ Returns «05:04:23 PM».

TestStr = Format(TestDateTime, «hh:mm:ss tt»)

‘ Returns «Saturday, Jan 27 2001».

TestStr = Format(TestDateTime, «dddd, MMM d yyyy»)

‘ Returns «17:04:23».

TestStr = Format(TestDateTime, «HH:mm:ss»)

‘ Returns «23».

TestStr = Format(23)

‘ User-defined numeric formats.

‘ Returns «5,459.40».

TestStr = Format(5459.4, «##,##0.00»)

‘ Returns «334.90».

TestStr = Format(334.9, «###0.00»)

‘ Returns «500.00%».

TestStr = Format(5, «0.00%»)

.NET Framework

Доступно с 1.1
Silverlight

Доступно с 2.0

Format
Str
Класс Strings
Пространство имен Microsoft.VisualBasic
Сводка по работе со строками (Visual Basic)

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

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.

Понравилась статья? Поделить с друзьями:
  • Vba excel разбить строку по символу
  • Vba excel разбить строку по разделителям
  • Vba excel разбить строку на массив
  • Vba excel рабочий день
  • Vba excel рабочие дни