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

Студворк — интернет-сервис помощи студентам

Суть в том, что осталась последняя пресдача, есть задачи и есть решение на них, нужно помочь объяснить само решение, помогите кто чем может, или в асю напишите 401996793, заранее спасибо

Запишите 4-е макроса которые бы меняли формат ячейки на денежный – рубли, доллары, английские фунты и евро. Создайте новое меню с соответствующими пунктами. При выборе пользователем пункта вашего меню ячейка должна форматироваться в нужный денежный формат.

Visual Basic
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
Sub menu()
Set myMenuBar = CommandBars.ActiveMenuBar
Set newMenu = myMenuBar.Controls.Add(Type:=msoCon trolPopup, Temporary:=True)
newMenu.Caption = "Формат ячеек"
Set dm = newMenu.Controls.Add(Type:=msoContr olButton)
dm.OnAction = "Макрос1"
dm.Caption = "Рубли"
Set nm = newMenu.Controls.Add(Type:=msoContr olButton)
nm.OnAction = "Макрос2"
nm.Caption = "Доллар"
Set lm = newMenu.Controls.Add(Type:=msoContr olButton)
lm.OnAction = "Макрос3"
lm.Caption = "Английский фунт"
Set km = newMenu.Controls.Add(Type:=msoContr olButton)
km.OnAction = "Макрос4"
km.Caption = "Евро"
End Sub

Воспользовавшись функциями MsgBox и InputBox задайте пользователю следующие вопросы
Фамилия Имя
Год рождения
Образование
Пол
Семейное положение
Ответы занесите в таблицу расположенную в Excel.

Visual Basic
1
2
3
4
5
6
7
8
9
10
Sub stdial2()
For i = 1 To 2
Cells(i + 1, 1).Value = InputBox("Введите свою фамилию")
Cells(i + 1, 2).Value = InputBox("Введите свое имя")
Cells(i + 1, 3).Value = InputBox("Введите год рождения")
Cells(i + 1, 4).Value = InputBox("Какое у вас образование?")
Cells(i + 1, 5).Value = InputBox("Ваш пол?")
Cells(i + 1, 6).Value = InputBox("Ваше семейное положение")
Next i
End Sub

. С помощью функции MsgBox задайте пользователю 5-ть вопросов с возможностью ответа Да/Нет/Отмена. После 5-ого вопроса выдайте сколько было ответов Да, сколько Нет, сколько Отмена.

Visual Basic
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
Sub stdial3()
da = 0
net = 0
otm = 0
c = MsgBox("Отформатировать текст?", vbYesNoCancel)
If c = vbYes Then da = da + 1
If c = vbNo Then net = net + 1
If c = vbCancel Then otm = otm + 1
c = MsgBox(" Увеличить шрифт?", vbYesNoCancel)
If c = vbYes Then da = da + 1
If c = vbNo Then net = net + 1
If c = vbCancel Then otm = otm + 1
c = MsgBox("Удалить файл?", vbYesNoCancel)
If c = vbYes Then da = da + 1
If c = vbNo Then net = net + 1
If c = vbCancel Then otm = otm + 1
c = MsgBox("Сделать копию документа?", vbYesNoCancel)
If c = vbYes Then da = da + 1
If c = vbNo Then net = net + 1
If c = vbCancel Then otm = otm + 1
c = MsgBox("Открыть документ?", vbYesNoCancel)
If c = vbYes Then da = da + 1
If c = vbNo Then net = net + 1
If c = vbCancel Then otm = otm + 1
MsgBox ("Да=" & da & " Нет=" & net & " Отмена=" & otm & " ")
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

You are free to use this image on your website, templates, etc, Please provide us with an attribution linkArticle Link to be Hyperlinked
For eg:
Source: VBA Format (wallstreetmojo.com)

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

Содержание

  1. Форматирование чисел
  2. Функция Format()
  3. Финансовые функции
  4. Функция FormatCurrency
  5. Синтаксис
  6. Settings
  7. Замечания
  8. См. также
  9. Поддержка и обратная связь
  10. Типы данных Number и Currency (свойство Format)
  11. Settings
  12. Предопределенные форматы
  13. Пользовательские форматы
  14. Замечания
  15. Примеры
  16. См. также
  17. Поддержка и обратная связь

Форматирование чисел

Для форматирования чисел предназначены следующие функции:

  • FormatNumber() — возвращает строковое представление числа в соответствии с заданным форматом. Синтаксис функции:
  • FormatPercent() — возвращает строковое представление числа в виде процентов в соответствии с заданным форматом. Значение умножается на 100 и в конец добавляется символ процента ( % ). Формат функции:
  • FormatCurrency() — возвращает строковое представление числа в денежном формате. В конце добавляется символ валюты. Формат функции:

Параметры в функциях FormatNumber() , FormatPercent() и FormatCurrency() имеют следующий смысл:

  • NumDigitsAfterDecimal — задает количество цифр после десятичной точки. По умолчанию параметр имеет значение -1 , которое означает, что используются региональные настройки. Пример:
  • IncludeLeadingDigit — определяет нужно ли отображать нулевую целую часть числа. Если указана константа vbTrue (или число -1 ), то нуль отображается, если vbFalse (или число 0 ) — то нет. По умолчанию параметр имеет значение константы vbUseDefault ( -2 ), которое означает, что будут использоваться региональные настройки. Пример:
  • UseParensForNegativeNumbers — если указана константа vbTrue (или число -1 ), то отрицательные значение будут отображаться внутри круглых скобок без знака числа, если vbFalse (или число 0 ) — то нет. По умолчанию параметр имеет значение константы vbUseDefault ( -2 ), которое означает, что будут использоваться региональные настройки. Пример:
  • GroupDigits — если указана константа vbTrue (или число -1 ), то тысячные группы будут разделяться через символ, указанный в региональных настройках (например, через пробел), если vbFalse (или число 0 ) — то нет. По умолчанию параметр имеет значение константы vbUseDefault ( -2 ), которое означает, что будут использоваться региональные настройки. Пример:

Функция Format()

Форматировать числа позволяет также функция Format() . Помимо чисел можно отформатировать и вывод значения даты и времени, а также строк. Формат функции:

Необязательный параметр Format задает выражение формата, параметр FirstDayOfWeek — первый день недели (константы vbMonday , vbTuesday , vbWednesday , vbThursday , vbFriday , vbSaturday , vbSunday (значение по умолчанию) и vbUseSystemDayOfWeek ), а параметр FirstWeekOfYear — первую неделю года (константы vbFirstJan1 (значение по умолчанию), vbFirstFullWeek , vbFirstFourDays и vbUseSystem ).

В параметре Format указываются следующие значения в виде строки:

  • General Number — отображает число без разделителя тысячных групп:
  • Fixed — выводит число без разделителя тысячных групп с двумя цифрами после десятичной точки:
  • Standard — отображает число с разделителями тысячных групп и двумя цифрами после десятичной точки:
  • Percent — возвращает строковое представление числа в виде процентов. Значение умножается на 100 и в конец добавляется символ процента ( % ). Число отображается без разделителя тысячных групп с двумя цифрами после десятичной точки:
  • Currency — денежный формат. Число отображается с разделителями тысячных групп, двумя цифрами после десятичной точки и символа валюты в зависимости от региональных настроек:
  • Scientific — формат с плавающей десятичной точкой:
  • Yes/No — отображает значение Нет , если число равно 0 , и Да — в противном случае:
  • True/False — выводит значение Ложь , если число равно 0 , и Истина — в противном случае:
  • On/Off — отображает значение Выкл , если число равно 0 , и Вкл — в противном случае:
  • General Date — выводит дату и/или время в соответствии с региональными настройками:
  • Long Date — отображает дату в соответствии с полным форматом:
  • Medium Date — выводит дату в соответствии со средним форматом:
  • Short Date — отображает дату в соответствии с сокращенным форматом:
  • Long Time — выводит часы, минуты и секунды в соответствии с полным форматом:
  • Medium Time — отображает часы и минуты в 12-часовом формате:
  • Short Time — выводит часы и минуты в 24-часовом формате:

В параметре Format можно также указать шаблон с пользовательским форматом. В этом случае в строке используются следующие специальные символы:

  • 0 — отображает цифру или нуль, если цифры нет:
  • # — отображает цифру или ничего, если цифры нет:
  • . (точка) — резервирует позицию десятичной точки:
  • , (запятая) — резервирует позицию разделителя тысячных групп:
  • % — значение умножается на 100 и в позицию символа-заполнителя добавляется символ процента ( % ):
  • E- и e- — отображение числа в научном формате. Знак порядка отображается только для отрицательных значений:
  • E+ и e+ — отображение числа в научном формате. Знак порядка отображается в любом случае:
  • yy — год из двух цифр (от «00» до «99» );
  • yyyy — год из четырех цифр (например, «2012» );
  • m — номер месяца без предваряющего нуля (от «1» до «12» ). Если перед спецсимволом m стоит спецсимвол h или hh , то выводятся минуты без предваряющего нуля:
  • mm — номер месяца с предваряющим нулем (от «01» до «12» ). Если перед спецсимволом mm стоит спецсимвол h или hh , то выводятся минуты с предваряющим нулем:
  • mmm — аббревиатура месяца в зависимости от настроек локали (например, «сен» для сентября);
  • mmmm — название месяца в зависимости от настроек локали (например, «Сентябрь» );
  • d — номер дня в месяце без предваряющего нуля (от «1» до «31» );
  • dd — номер дня в месяце с предваряющим нулем (от «01» до «31» );
  • y — номер дня с начала года (от «1» до «366» );
  • q — номер квартала (от «1» до «4» );
  • ww — номер недели в году (от «1» до «54» );
  • w — номер дня недели ( «1» — для воскресенья, «7» — для субботы);
  • ddd — аббревиатура дня недели в зависимости от настроек локали (например, «Чт» для четверга);
  • dddd — название дня недели в зависимости от региональных настроек (например, «четверг» );
  • h — часы без предваряющего нуля (от «0» до «23» );
  • hh — часы с предваряющим нулем (от «00» до «23» );
  • n — минуты без предваряющего нуля (от «0» до «59» );
  • nn — минуты с предваряющим нулем (от «00» до «59» );
  • s — секунды без предваряющего нуля (от «0» до «59» );
  • ss — секунды с предваряющим нулем (от «00» до «59» );
  • ddddd — отображает дату в соответствии с сокращенным форматом:
  • dddddd — отображает дату в соответствии с полным форматом:
  • c — отображает дату и время в соответствии с сокращенным форматом:
  • / — символ-разделитель для даты в зависимости от региональных настроек:
  • : — символ-разделитель для времени в зависимости от региональных настроек:
  • @ — символ или пробел, если символа нет. Если символов не хватает, то по умолчанию (если не указан спецсимвол ! ) строка выравнивается по правому краю. Пример:
  • ! — задает выравнивание по левому краю:
  • & — символ или ничего, если символа нет:
  • — отображает все буквы в нижнем регистре:
  • > — отображает все буквы в верхнем регистре:

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

Если нужно вывести защитный слеш ( ), то его следует удвоить:

При форматировании чисел шаблон может содержать от одной до четырех секций, разделяемых с помощью точки с запятой ( ; ):

  • одна секция только — шаблон относится ко всему значению;
  • две секции — первая секция задает шаблон для положительных значений и нуля, а вторая секция — для отрицательных значений:
  • три секции — первая секция задает шаблон для положительных значений, вторая секция — для отрицательных значений, а третья секция — для нуля:
  • четыре секции — первая секция задает шаблон для положительных значений, вторая секция — для отрицательных значений, третья секция — для нуля, а четвертая секция — для значения Null :

При форматировании строки шаблон может содержать от одной до двух секций, разделяемых с помощью точки с запятой ( ; ):

  • одна секция только — шаблон относится ко всей строке;
  • две секции — первая секция задает шаблон для строки, а вторая секция — для значения Null и пустой строки:

Функция Format() возвращает значение типа Variant (String) . Чтобы получить значение типа String следует использовать функцию Format$() , имеющую тот же самый формат. Пример:

Финансовые функции

Язык VBA содержит много встроенных функций, предназначенных для выполнения финансовых операций. Например, функции DDB() , SLN() и SYD() позволяют вычислить величину амортизации имущества различными способами. Все финансовые функции являются специфическими и не представляют особого интереса для большинства программистов, поэтому мы не будем рассматривать их в этой книге. За подробной информацией по финансовым функциям обращайтесь к документации.

Статьи по Visual Basic for Applications (VBA)

Помощь сайту

ПАО Сбербанк:
Счет: 40817810855006152256
Реквизиты банка:
Наименование: СЕВЕРО-ЗАПАДНЫЙ БАНК ПАО СБЕРБАНК
Корреспондентский счет: 30101810500000000653
БИК: 044030653
КПП: 784243001
ОКПО: 09171401
ОКОНХ: 96130
Скриншот реквизитов

Источник

Функция FormatCurrency

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

Синтаксис

FormatCurrency(Expression, [ NumDigitsAfterDecimal, [ IncludeLeadingDigit, [ UseParensForNegativeNumbers, [ GroupDigits ]]]]])

Синтаксис функции FormatCurrency состоит из таких частей:

Part Описание
Expression Обязательный атрибут. Выражение для форматирования.
NumDigitsAfterDecimal Необязательный параметр. Числовое значение, указывающее, сколько знаков отображается справа от десятичного разделителя. Значение по умолчанию — -1, указывающее, что используются региональные параметры компьютера.
IncludeLeadingDigit Необязательный параметр. Константа с тремя состояниями, определяющая, будет ли отображаться нуль в начале дробных значений. Значения см. в разделе параметров.
UseParensForNegativeNumbers Необязательный параметр. Константа с тремя состояниями, определяющая, следует ли помещать отрицательные числа в скобки. Значения см. в разделе параметров.
GroupDigits Необязательный параметр. Константная tristate, указывающая, группируются ли числа с помощью разделителя групп, заданного в региональных параметрах компьютера. Значения см. в разделе параметров.

Settings

Аргументы IncludeLeadingDigit, UseParensForNegativeNumbers и GroupDigits имеют следующие параметры:

Константа Значение Описание
vbTrue –1 Верно
vbFalse 0 Неверно
vbUseDefault –2 Использование настройки, определенной в региональных параметрах компьютера.

Замечания

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

Вся информация о параметрах предоставлена на вкладке Regional Settings Currency (Валюта региональных параметров), за исключением информации про нуль вначале, отображенной на вкладке Number (Число).

См. также

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

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

Источник

Типы данных Number и Currency (свойство Format)

Область применения: Access 2013 | Access 2016

Для свойства Format можно задать стандартные числовые форматы или настраиваемые числовые форматы для типов данных Number и Currency.

Settings

Предопределенные форматы

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

Setting Описание
General Number (по умолчанию) Отображение введенного числа.
Валюта Используйте разделитель тысяч; следуйте параметрам, указанным в региональных параметрах Windows, для отрицательных сумм, десятичных и денежных символов, а также десятичных разрядов.
Евро Используйте символ евро (), независимо от символа валюты, указанного в региональных параметрах Windows.
ИСПРАВЛЕНО Отображение по крайней мере одной цифры; следуйте параметрам, указанным в региональных параметрах Windows, для отрицательных сумм, десятичных и денежных символов, а также десятичных разрядов.
Стандартный Используйте разделитель тысяч; Следуйте параметрам, указанным в региональных параметрах Windows, для отрицательных значений, десятичных символов и десятичных разрядов.
Процент Умножьте значение на 100 и добавьте знак процента (%); Следуйте параметрам, указанным в региональных параметрах Windows, для отрицательных значений, десятичных символов и десятичных разрядов.
Scientific Используется стандартное экспоненциальное представление.

Пользовательские форматы

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

Section Описание
Первый Формат положительных чисел.
Секунды Формат отрицательных чисел.
Третий Формат для нулевых значений.
Четвертый Формат значений NULL .

Например, можно использовать следующий пользовательский формат валюты:

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

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

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

Символ Описание
. (точка) Десятичный разделитель. Разделители задаются в региональных параметрах Windows.
, (запятая) Разделитель групп разрядов.
0 Заполнитель цифры. Отображение цифры или 0.
# Заполнитель цифры. Отображает цифру или ничего не отображает.
$ Отображение литерала «$».
% Процент. Значение умножается на 100 и добавляется знак процента.
E- или e- Научная нотация со знаком минус (-) рядом с отрицательными экспонентами и ничего рядом с положительными экспонентами. Этот символ должен использоваться с другими символами, как в 0.00E-00 или 0.00E00.
E+ или e+ Научная нотация со знаком «минус» (-) рядом с отрицательными экспонентами и знаком «плюс» (+) рядом с положительными экспонентами. Этот символ должен использоваться с другими символами, как в 0,00E+00.

Замечания

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

Предопределенные форматы валют и евро соответствуют параметрам в региональных параметрах Windows. Их можно переопределить, введя собственный формат валюты.

Примеры

Ниже приведены примеры стандартных числовых форматов.

Setting Данные Отображение
General Number 3456.789 -3456.789 $213.21 3456.789 -3456.789 $213.21
Валюта 3456.789 -3456.789 3 456,79 долл. США (3 456,79 долл. США)
ИСПРАВЛЕНО 3456.789 -3456.789 3.56645 3456.79 -3456.79 3.57
Стандартный 3456.789 3,456.79
Процент 3 0.45 300% 45%
Scientific 3456.789 -3456.789 3.46E+03 -3.46E+03

Ниже приведены примеры пользовательских числовых форматов.

Setting Описание
0;(0);;»Null» Отображение положительных значений в обычном режиме; отображение отрицательных значений в круглых скобках; если значение равно Null, отображается слово Null.
+0.0;-0.0;0.0 Отображение знака плюса (+) или минуса (-) с положительными или отрицательными числами; отображается значение 0,0, если значение равно нулю.

См. также

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

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

Источник

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