Visual basic excel формат ячейки в

Свойства ячейки, часто используемые в коде VBA Excel. Демонстрация свойств ячейки, как структурной единицы объекта Range, на простых примерах.

Объект Range в VBA Excel представляет диапазон ячеек. Он (объект Range) может описывать любой диапазон, начиная от одной ячейки и заканчивая сразу всеми ячейками рабочего листа.

Примеры диапазонов:

  • Одна ячейка – Range("A1").
  • Девять ячеек – Range("A1:С3").
  • Весь рабочий лист в Excel 2016 – Range("1:1048576").

Для справки: выражение Range("1:1048576") описывает диапазон с 1 по 1048576 строку, где число 1048576 – это номер последней строки на рабочем листе Excel 2016.

В VBA Excel есть свойство Cells объекта Range, которое позволяет обратиться к одной ячейке в указанном диапазоне (возвращает объект Range в виде одной ячейки). Если в коде используется свойство Cells без указания диапазона, значит оно относится ко всему диапазону активного рабочего листа.

Примеры обращения к одной ячейке:

  • Cells(1000), где 1000 – порядковый номер ячейки на рабочем листе, возвращает ячейку «ALL1».
  • Cells(50, 20), где 50 – номер строки рабочего листа, а 20 – номер столбца, возвращает ячейку «T50».
  • Range("A1:C3").Cells(6), где «A1:C3» – заданный диапазон, а 6 – порядковый номер ячейки в этом диапазоне, возвращает ячейку «C2».

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

Подробнее о том, как обратиться к ячейке, смотрите в статье: Ячейки (обращение, запись, чтение, очистка).

В этой статье мы рассмотрим свойства объекта Range, применимые, в том числе, к диапазону, состоящему из одной ячейки.

Еще надо добавить, что свойства и методы объектов отделяются от объектов точкой, как в третьем примере обращения к одной ячейке: Range("A1:C3").Cells(6).

Свойства ячейки (объекта Range)

Свойство Описание
Address Возвращает адрес ячейки (диапазона).
Borders Возвращает коллекцию Borders, представляющую границы ячейки (диапазона). Подробнее…
Cells Возвращает объект Range, представляющий коллекцию всех ячеек заданного диапазона. Указав номер строки и номер столбца или порядковый номер ячейки в диапазоне, мы получаем конкретную ячейку. Подробнее…
Characters Возвращает подстроку в размере указанного количества символов из текста, содержащегося в ячейке. Подробнее…
Column Возвращает номер столбца ячейки (первого столбца диапазона). Подробнее…
ColumnWidth Возвращает или задает ширину ячейки в пунктах (ширину всех столбцов в указанном диапазоне).
Comment Возвращает комментарий, связанный с ячейкой (с левой верхней ячейкой диапазона).
CurrentRegion Возвращает прямоугольный диапазон, ограниченный пустыми строками и столбцами. Очень полезное свойство для возвращения рабочей таблицы, а также определения номера последней заполненной строки.
EntireColumn Возвращает весь столбец (столбцы), в котором содержится ячейка (диапазон). Диапазон может содержаться и в одном столбце, например, Range("A1:A20").
EntireRow Возвращает всю строку (строки), в которой содержится ячейка (диапазон). Диапазон может содержаться и в одной строке, например, Range("A2:H2").
Font Возвращает объект Font, представляющий шрифт указанного объекта. Подробнее о цвете шрифта…
HorizontalAlignment Возвращает или задает значение горизонтального выравнивания содержимого ячейки (диапазона). Подробнее…
Interior Возвращает объект Interior, представляющий внутреннюю область ячейки (диапазона). Применяется, главным образом, для возвращения или назначения цвета заливки (фона) ячейки (диапазона). Подробнее…
Name Возвращает или задает имя ячейки (диапазона).
NumberFormat Возвращает или задает код числового формата для ячейки (диапазона). Примеры кодов числовых форматов можно посмотреть, открыв для любой ячейки на рабочем листе Excel диалоговое окно «Формат ячеек», на вкладке «(все форматы)». Свойство NumberFormat диапазона возвращает значение NULL, за исключением тех случаев, когда все ячейки в диапазоне имеют одинаковый числовой формат. Если нужно присвоить ячейке текстовый формат, записывается так: Range("A1").NumberFormat = "@". Общий формат: Range("A1").NumberFormat = "General".
Offset Возвращает объект Range, смещенный относительно первоначального диапазона на указанное количество строк и столбцов. Подробнее…
Resize Изменяет размер первоначального диапазона до указанного количества строк и столбцов. Строки добавляются или удаляются снизу, столбцы – справа. Подробнее…
Row Возвращает номер строки ячейки (первой строки диапазона). Подробнее…
RowHeight Возвращает или задает высоту ячейки в пунктах (высоту всех строк в указанном диапазоне).
Text Возвращает форматированный текст, содержащийся в ячейке. Свойство Text диапазона возвращает значение NULL, за исключением тех случаев, когда все ячейки в диапазоне имеют одинаковое содержимое и один формат. Предназначено только для чтения. Подробнее…
Value Возвращает или задает значение ячейки, в том числе с отображением значений в формате Currency и Date. Тип данных Variant. Value является свойством ячейки по умолчанию, поэтому в коде его можно не указывать.
Value2 Возвращает или задает значение ячейки. Тип данных Variant. Значения в формате Currency и Date будут отображены в виде чисел с типом данных Double.
VerticalAlignment Возвращает или задает значение вертикального выравнивания содержимого ячейки (диапазона). Подробнее…

В таблице представлены не все свойства объекта Range. С полным списком вы можете ознакомиться не сайте разработчика.

Простые примеры для начинающих

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

Учтите, что в одном программном модуле у всех процедур должны быть разные имена. Если вы уже копировали в модуль подпрограммы с именами Primer1, Primer2 и т.д., удалите их или создайте еще один стандартный модуль.

Форматирование ячеек

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

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

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

27

28

29

30

31

32

33

34

35

36

37

38

Sub Primer1()

MsgBox «Зальем ячейку A1 зеленым цветом и запишем в ячейку B1 текст: «Ячейка A1 зеленая!»»

Range(«A1»).Interior.Color = vbGreen

Range(«B1»).Value = «Ячейка A1 зеленая!»

MsgBox «Сделаем высоту строки, в которой находится ячейка A2, в 2 раза больше высоты ячейки A1, « _

& «а в ячейку B1 вставим текст: «Наша строка стала в 2 раза выше первой строки!»»

Range(«A2»).RowHeight = Range(«A1»).RowHeight * 2

Range(«B2»).Value = «Наша строка стала в 2 раза выше первой строки!»

MsgBox «Запишем в ячейку A3 высоту 2 строки, а в ячейку B3 вставим текст: «Такова высота второй строки!»»

Range(«A3»).Value = Range(«A2»).RowHeight

Range(«B3»).Value = «Такова высота второй строки!»

MsgBox «Применим к столбцу, в котором содержится ячейка B1, метод AutoFit для автоподбора ширины»

Range(«B1»).EntireColumn.AutoFit

MsgBox «Выделим текст в ячейке B2 красным цветом и выровним его по центру (по вертикали)»

Range(«B2»).Font.Color = vbRed

Range(«B2»).VerticalAlignment = xlCenter

MsgBox «Добавим к ячейкам диапазона A1:B3 границы»

Range(«A1:B3»).Borders.LineStyle = True

MsgBox «Сделаем границы ячеек в диапазоне A1:B3 двойными»

Range(«A1:B3»).Borders.LineStyle = xlDouble

MsgBox «Очистим ячейки диапазона A1:B3 от заливки, выравнивания, границ и содержимого»

Range(«A1:B3»).Clear

MsgBox «Присвоим высоте второй строки высоту первой, а ширине второго столбца — ширину первого»

Range(«A2»).RowHeight = Range(«A1»).RowHeight

Range(«B1»).ColumnWidth = Range(«A1»).ColumnWidth

MsgBox «Демонстрация форматирования ячеек закончена!»

End Sub

Вычисления в ячейках (свойство Value)

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

Обратите внимание, что разделителем дробной части у чисел в VBA Excel является точка, а не запятая.

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

Sub Primer2()

MsgBox «Запишем в ячейку A1 число 25.3, а в ячейку B1 — число 34.42»

Range(«A1»).Value = 25.3

Range(«B1»).Value = 34.42

MsgBox «Запишем в ячейку C1 произведение чисел, содержащихся в ячейках A1 и B1»

Range(«C1»).Value = Range(«A1»).Value * Range(«B1»).Value

MsgBox «Запишем в ячейку D1 формулу, которая перемножает числа в ячейках A1 и B1»

Range(«D1»).Value = «=A1*B1»

MsgBox «Заменим содержимое ячеек A1 и B1 на числа 6.258 и 54.1, а также активируем ячейку D1»

Range(«A1»).Value = 6.258

Range(«B1»).Value = 54.1

Range(«D1»).Activate

MsgBox «Мы видим, что в ячейке D1 произведение изменилось, а в строке состояния отображается формула; « _

& «следующим шагом очищаем задействованные ячейки»

Range(«A1:D1»).Clear

MsgBox «Демонстрация вычислений в ячейках завершена!»

End Sub

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

Различие свойств Text, Value и Value2

Построение с помощью кода VBA Excel таблицы с результатами сравнения того, как свойства Text, Value и Value2 возвращают число, дату и текст.

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

27

28

29

30

31

32

33

34

35

36

37

38

39

40

41

42

43

44

45

46

47

48

49

50

51

52

53

54

55

56

Sub Primer3()

‘Присваиваем ячейкам всей таблицы общий формат на тот

‘случай, если формат отдельных ячеек ранее менялся

Range(«A1:E4»).NumberFormat = «General»

‘добавляем сетку (границы ячеек)

Range(«A1:E4»).Borders.LineStyle = True

‘Создаем строку заголовков

Range(«A1») = «Значение»

Range(«B1») = «Код формата» ‘формат соседней ячейки в столбце A

Range(«C1») = «Свойство Text»

Range(«D1») = «Свойство Value»

Range(«E1») = «Свойство Value2»

‘Назначаем строке заголовков жирный шрифт

Range(«A1:E1»).Font.Bold = True

‘Задаем форматы ячейкам A2, A3 и A4

‘Ячейка A2 — числовой формат с разделителем триад и двумя знаками после запятой

‘Ячейка A3 — формат даты «ДД.ММ.ГГГГ»

‘Ячейка A4 — текстовый формат

Range(«A2»).NumberFormat = «# ##0.00»

Range(«A3»).NumberFormat = «dd.mm.yyyy»

Range(«A4»).NumberFormat = «@»

‘Заполняем ячейки A2, A3 и A4 значениями

Range(«A2») = 2362.4568

Range(«A3») = CDate(«01.01.2021»)

‘Функция CDate преобразует текстовый аргумент в формат даты

Range(«A4») = «Озеро Байкал»

‘Заполняем ячейки B2, B3 и B4 кодами форматов соседних ячеек в столбце A

Range(«B2») = Range(«A2»).NumberFormat

Range(«B3») = Range(«A3»).NumberFormat

Range(«B4») = Range(«A4»).NumberFormat

‘Присваиваем ячейкам C2-C4 значения свойств Text ячеек A2-A4

Range(«C2») = Range(«A2»).Text

Range(«C3») = Range(«A3»).Text

Range(«C4») = Range(«A4»).Text

‘Присваиваем ячейкам D2-D4 значения свойств Value ячеек A2-A4

Range(«D2») = Range(«A2»).Value

Range(«D3») = Range(«A3»).Value

Range(«D4») = Range(«A4»).Value

‘Присваиваем ячейкам E2-E4 значения свойств Value2 ячеек A2-A4

Range(«E2») = Range(«A2»).Value2

Range(«E3») = Range(«A3»).Value2

Range(«E4») = Range(«A4»).Value2

‘Применяем к таблице автоподбор ширины столбцов

Range(«A1:E4»).EntireColumn.AutoFit

End Sub

Результат работы кода:

Сравнение свойств ячейки Text, Value и Value2

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


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

Formatting Cells Number

General

Range("A1").NumberFormat = "General"

Number

Range("A1").NumberFormat = "0.00"

Currency

Range("A1").NumberFormat = "$#,##0.00"

Accounting

Range("A1").NumberFormat = "_($* #,##0.00_);_($* (#,##0.00);_($* ""-""??_);_(@_)"

Date

Range("A1").NumberFormat = "yyyy-mm-dd;@"

Time

Range("A1").NumberFormat = "h:mm:ss AM/PM;@"

Percentage

Range("A1").NumberFormat = "0.00%"

Fraction

Range("A1").NumberFormat = "# ?/?"

Scientific

Range("A1").NumberFormat = "0.00E+00"

Text

Range("A1").NumberFormat = "@"

Special

Range("A1").NumberFormat = "00000"

Custom

Range("A1").NumberFormat = "$#,##0.00_);[Red]($#,##0.00)"

Formatting Cells Alignment

Text Alignment

Horizontal

The value of this property can be set to one of the constants: xlGeneral, xlCenter, xlDistributed, xlJustify, xlLeft, xlRight.

The following code sets the horizontal alignment of cell A1 to center.

Range("A1").HorizontalAlignment = xlCenter

Vertical

The value of this property can be set to one of the constants: xlBottom, xlCenter, xlDistributed, xlJustify, xlTop.

The following code sets the vertical alignment of cell A1 to bottom.

Range("A1").VerticalAlignment = xlBottom

Text Control

Wrap Text

This example formats cell A1 so that the text wraps within the cell.

Range("A1").WrapText = True

Shrink To Fit

This example causes text in row one to automatically shrink to fit in the available column width.

Rows(1).ShrinkToFit = True

Merge Cells

This example merge range A1:A4 to a large one.

Range("A1:A4").MergeCells = True

Right-to-left

Text direction

The value of this property can be set to one of the constants: xlRTL (right-to-left), xlLTR (left-to-right), or xlContext (context).

The following code example sets the reading order of cell A1 to xlRTL (right-to-left).

Range("A1").ReadingOrder = xlRTL

Orientation

The value of this property can be set to an integer value from –90 to 90 degrees or to one of the following constants: xlDownward, xlHorizontal, xlUpward, xlVertical.

The following code example sets the orientation of cell A1 to xlHorizontal.

Range("A1").Orientation = xlHorizontal

Font

Font Name

The value of this property can be set to one of the fonts: Calibri, Times new Roman, Arial

The following code sets the font name of range A1:A5 to Calibri.

Range("A1:A5").Font.Name = "Calibri"

Font Style

The value of this property can be set to one of the constants: Regular, Bold, Italic, Bold Italic.

The following code sets the font style of range A1:A5 to Italic.

Range("A1:A5").Font.FontStyle = "Italic"

Font Size

The value of this property can be set to an integer value from 1 to 409.

The following code sets the font size of cell A1 to 14.

Range("A1").Font.Size = 14

Underline

The value of this property can be set to one of the constants: xlUnderlineStyleNone, xlUnderlineStyleSingle, xlUnderlineStyleDouble, xlUnderlineStyleSingleAccounting, xlUnderlineStyleDoubleAccounting.

The following code sets the font of cell A1 to xlUnderlineStyleDouble (double underline).

Range("A1").Font.Underline = xlUnderlineStyleDouble

Font Color

The value of this property can be set to one of the standard colors: vbBlack, vbRed, vbGreen, vbYellow, vbBlue, vbMagenta, vbCyan, vbWhite or an integer value from 0 to 16,581,375.

To assist you with specifying the color of anything, the VBA is equipped with a function named RGB. Its syntax is:

Function RGB(RedValue As Byte, GreenValue As Byte, BlueValue As Byte) As long

This function takes three arguments and each must hold a value between 0 and 255. The first argument represents the ratio of red of the color. The second argument represents the green ratio of the color. The last argument represents the blue of the color. After the function has been called, it produces a number whose maximum value can be 255 * 255 * 255 = 16,581,375, which represents a color.

The following code sets the font color of cell A1 to vbBlack (Black).

Range("A1").Font.Color = vbBlack

The following code sets the font color of cell A1 to 0 (Black).

Range("A1").Font.Color = 0

The following code sets the font color of cell A1 to RGB(0, 0, 0) (Black).

Range("A1").Font.Color = RGB(0, 0, 0)

Font Effects

Strikethrough

True if the font is struck through with a horizontal line.

The following code sets the font of cell A1 to strikethrough.

Range("A1").Font.Strikethrough = True

Subscript

True if the font is formatted as subscript. False by default.

The following code sets the font of cell A1 to Subscript.

Range("A1").Font.Subscript = True

Superscript

True if the font is formatted as superscript; False by default.

The following code sets the font of cell A1 to Superscript.

Range("A1").Font.Superscript = True

Border

Border Index

Using VBA you can choose to create borders for the different edges of a range of cells:

  1. xlDiagonalDown (Border running from the upper left-hand corner to the lower right of each cell in the range).
  2. xlDiagonalUp (Border running from the lower left-hand corner to the upper right of each cell in the range).
  3. xlEdgeBottom (Border at the bottom of the range).
  4. xlEdgeLeft (Border at the left-hand edge of the range).
  5. xlEdgeRight (Border at the right-hand edge of the range).
  6. xlEdgeTop (Border at the top of the range).
  7. xlInsideHorizontal (Horizontal borders for all cells in the range except borders on the outside of the range).
  8. xlInsideVertical (Vertical borders for all the cells in the range except borders on the outside of the range).

Line Style

The value of this property can be set to one of the constants: xlContinuous (Continuous line), xlDash (Dashed line), xlDashDot (Alternating dashes and dots), xlDashDotDot (Dash followed by two dots), xlDot (Dotted line), xlDouble (Double line), xlLineStyleNone (No line), xlSlantDashDot (Slanted dashes).

The following code example sets the border on the bottom edge of cell A1 with continuous line.

Range("A1").Borders(xlEdgeBottom).LineStyle = xlContinuous

The following code example removes the border on the bottom edge of cell A1.

Range("A1").Borders(xlEdgeBottom).LineStyle = xlNone

Line Thickness

The value of this property can be set to one of the constants: xlHairline (Hairline, thinnest border), xlMedium (Medium), xlThick (Thick, widest border), xlThin (Thin).

The following code example sets the thickness of the border created to xlThin (Thin).

Range("A1").Borders(xlEdgeBottom).Weight = xlThin

Line Color

The value of this property can be set to one of the standard colors: vbBlack, vbRed, vbGreen, vbYellow, vbBlue, vbMagenta, vbCyan, vbWhite or an integer value from 0 to 16,581,375.

The following code example sets the color of the border on the bottom edge to green.

Range("A1").Borders(xlEdgeBottom).Color = vbGreen

You can also use the RGB function to create a color value.

The following example sets the color of the bottom border of cell A1 with RGB fuction.

Range("A1").Borders(xlEdgeBottom).Color = RGB(255, 0, 0)

Fill

Pattern Style

The value of this property can be set to one of the constants:

  1. xlPatternAutomatic (Excel controls the pattern.)
  2. xlPatternChecker (Checkerboard.)
  3. xlPatternCrissCross (Criss-cross lines.)
  4. xlPatternDown (Dark diagonal lines running from the upper left to the lower right.)
  5. xlPatternGray16 (16% gray.)
  6. xlPatternGray25 (25% gray.)
  7. xlPatternGray50 (50% gray.)
  8. xlPatternGray75 (75% gray.)
  9. xlPatternGray8 (8% gray.)
  10. xlPatternGrid (Grid.)
  11. xlPatternHorizontal (Dark horizontal lines.)
  12. xlPatternLightDown (Light diagonal lines running from the upper left to the lower right.)
  13. xlPatternLightHorizontal (Light horizontal lines.)
  14. xlPatternLightUp (Light diagonal lines running from the lower left to the upper right.)
  15. xlPatternLightVertical (Light vertical bars.)
  16. xlPatternNone (No pattern.)
  17. xlPatternSemiGray75 (75% dark moiré.)
  18. xlPatternSolid (Solid color.)
  19. xlPatternUp (Dark diagonal lines running from the lower left to the upper right.)

Protection

Locking Cells

This property returns True if the object is locked, False if the object can be modified when the sheet is protected, or Null if the specified range contains both locked and unlocked cells.

The following code example unlocks cells A1:B22 on Sheet1 so that they can be modified when the sheet is protected.

Worksheets("Sheet1").Range("A1:B22").Locked = False
Worksheets("Sheet1").Protect

Hiding Formulas

This property returns True if the formula will be hidden when the worksheet is protected, Null if the specified range contains some cells with FormulaHidden equal to True and some cells with FormulaHidden equal to False.

Don’t confuse this property with the Hidden property. The formula will not be hidden if the workbook is protected and the worksheet is not, but only if the worksheet is protected.

The following code example hides the formulas in cells A1 and C1 on Sheet1 when the worksheet is protected.

Worksheets("Sheet1").Range("A1:C1").FormulaHidden = True

I have a «duration» column in an Excel sheet. Its cell format always changes — I want convert the duration from minutes to seconds, but because of the cell formatting it always gives me different answers.

I was thinking that before doing the conversion I could convert that cell format to text so that it will consider that as text value and not try to auto-format it.

Currently I am copying all data into Notepad and then saving it back to the Excel sheet to remove all of the previous format. Is there a way to automate setting a cell’s formatting to text using VBA?

Teamothy's user avatar

Teamothy

1,9903 gold badges15 silver badges24 bronze badges

asked Nov 25, 2011 at 6:10

Code Hungry's user avatar

Code HungryCode Hungry

3,87022 gold badges66 silver badges95 bronze badges

1

To answer your direct question, it is:

Range("A1").NumberFormat = "@"

Or

Cells(1,1).NumberFormat = "@"

However, I suggest changing the format to what you actually want displayed. This allows you to retain the data type in the cell and easily use cell formulas to manipulate the data.

answered Nov 25, 2011 at 20:03

Justin Self's user avatar

0

One point: you have to set NumberFormat property BEFORE loading the value into the cell. I had a nine digit number that still displayed as 9.14E+08 when the NumberFormat was set after the cell was loaded. Setting the property before loading the value made the number appear as I wanted, as straight text.

OR:

Could you try an autofit first:

Excel_Obj.Columns("A:V").EntireColumn.AutoFit

Teamothy's user avatar

Teamothy

1,9903 gold badges15 silver badges24 bronze badges

answered Apr 22, 2015 at 19:56

Dan McSweeney's user avatar

1

Well this should change your format to text.

Worksheets("Sheetname").Activate
Worksheets("SheetName").Columns(1).Select 'or Worksheets("SheetName").Range("A:A").Select
Selection.NumberFormat = "@"

answered Nov 25, 2011 at 20:02

Jon's user avatar

JonJon

4333 gold badges6 silver badges24 bronze badges

1

for large numbers that display with scientific notation set format to just ‘#’

answered Feb 21, 2019 at 18:08

Mark Freeman's user avatar

To prevent Scientific Notation

With Range(A:A)
    .NumberFormat = "@"
    .Value = .Formula
End With

Stefano Sansone's user avatar

answered Mar 14, 2022 at 13:02

Defgha's user avatar

Содержание

  1. Формат отображаемого значения
  2. Применение стилей к ячейкам листа
  3. VBA-макрос: заливка, шрифт, линии границ, ширина столбцов и высота строк
  4. Вывод сообщений о числовых значениях цветов
  5. Выравнивание по горизонтали
  6. Основные свойства объекта Font
  7. Синтаксис и параметры
  8. Именные форматы даты и времени
  9. Именованные форматы чисел
  10. Символы для форматов даты и времени
  11. Заливка ячейки цветом в VBA Excel
  12. Создание новых стилей
  13. Выравнивание по вертикали
  14. Зачем нужны именованные стили
  15. Описание VBA-макроса для формата ячеек таблицы Excel
  16. Использование предопределенных констант
  17. Изменение существующих стилей

Формат отображаемого значения

Когда мы из кода VBA Excel записываем в ячейку текстовое или другое значение, оно отображается в формате, присвоенном данной ячейке. Это может быть формат:

  • рабочего листа по умолчанию;
  • установленный для диапазона пользователем;
  • примененный к диапазону из кода VBA Excel.

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

У объекта Range есть свойство Font (шрифт), которое отвечает за форматирование (начертание) визуально отображаемого текста в ячейках рабочего листа. Его применение вызывает объект Font, который в свою очередь обладает собственным набором свойств, отвечающих за конкретный стиль начертания отображаемого значения.

Применение стилей к ячейкам листа

В Excel изначально установлено множество встроенных стилей. Найти их можно в меню Стили ячеек, которая расположена на вкладке Главная -> Стили.

Откроется галерея стилей (рисунок справа).

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

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

В процессе запыления данных сотрудниками отдела на некоторых листах были изменены форматы ячеек:

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

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

Макросы Excel прекрасно справляются с форматированием ячеек на рабочих листах. Кроме того, делают это быстро и в полностью автоматическом режиме. Воспользуемся этими преимуществами и для решения данной задачи напишем свой код VBA-макроса. Он поможет нам быстро и безопасно сбрасывать форматы на исходный предварительно заданный в шаблоне главной таблицы.

Чтобы написать свой код макроса откройте специальный VBA-редактор в Excel: «РАЗРАБОТЧИК»-«Код»-«Visual Basic» или нажмите комбинацию клавиш ALT+F11:

В редакторе создайте новый модуль выбрав инструмент «Insert»-«Module» и введите в него такой VBA-код макроса:

SubSbrosFormat()
IfTypeName(Selection) <>"Range"Then Exit Sub
WithSelection
.HorizontalAlignment = xlVAlignCenter
.VerticalAlignment = xlVAlignCenter
.WrapText =True
.Borders.LineStyle = xlContinuous
.Borders.Weight = xlThin
.Font.ColorIndex = xlColorIndexAutomatic
.Interior.ColorIndex = xlColorIndexAutomatic
.Columns.AutoFit
.Rows.AutoFit
End With
End Sub

Теперь если нам нужно сбросить форматирование таблицы на исходный формат отображения ее данных, выделите диапазон ячеек A1:E20 и запустите макрос: «РАЗРАБОЧТИК»-«Код»-«Макросы»-«SbrosFormat»-«Выполнить». Результат работы макроса изображен ниже на рисунке:

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

Вывод сообщений о числовых значениях цветов

Числовые значения цветов запомнить невозможно, поэтому часто возникает вопрос о том, как узнать числовое значение фона ячейки. Следующий код VBA Excel выводит сообщения о числовых значениях присвоенных ранее цветов.

Пример кода 2:

Sub ColorTest2()

MsgBox Range(“A1”).Interior.Color

MsgBox Range(“A4:D8”).Interior.Color

MsgBox Range(“C12:D17”).Cells(4).Interior.Color

MsgBox Cells(3, 6).Interior.Color

End Sub

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

Выравнивание по горизонтали

Для выравнивания текста в ячейках рабочего листа по горизонтали в VBA Excel используется свойство HorizontalAlignment объекта Range. Оно может принимать следующие значения:

Выравнивание Константа Значение
По левому краю xlLeft -4131
По центру xlCenter -4108
По правому краю xlRight -4152

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

Пример 1
Заполним три первые ячейки листа Excel текстом, соответствующим предполагаемому выравниванию. Затем применим к ним выравнивание по горизонтали, а в ячейках ниже выведем соответствующие значения констант.

1

2

3

4

5

6

7

8

9

10

11

12

13

14

Sub Primer1()

‘Заполняем ячейки текстом

Range(“A1”) = “Левая сторона”

Range(“B1”) = “Центр ячейки”

Range(“C1”) = “Правая сторона”

‘Применяем горизонтальное выравнивание

Range(“A1”).HorizontalAlignment = xlLeft

Range(“B1”).HorizontalAlignment = xlCenter

Range(“C1”).HorizontalAlignment = xlRight

‘Выводим значения констант

Range(“A2”) = “xlLeft = “ & xlLeft

Range(“B2”) = “xlCenter = “ & xlCenter

Range(“C2”) = “xlRight = “ & xlRight

End Sub

Основные свойства объекта Font

Свойство Описание Значения
Name наименование шрифта “Arial”, “Calibri”, “Courier New”, “Times New Roman” и т.д.
Size размер шрифта от 1 до 409 пунктов
Bold полужирное начертание True, False
Italic курсивное начертание True, False
FontStyle заменяет Bold и Italic “обычный”, “полужирный”, “курсив”, “полужирный курсив”
Superscript надстрочный текст True, False
Subscript подстрочный текст True, False
Underline подчеркнутый текст True, False
Color* цвет текста от 0 до 16777215

*Color – это не единственное свойство, отвечающее за цвет отображаемого текста в ячейке. Оно также может принимать и другие значения, кроме указанных в таблице. Смотрите подробности в статье Цвет текста (шрифта) в ячейке.

Синтаксис и параметры

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:

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

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–31). Если (m) следует после (h) или (hh), отображаются минуты.
mm Месяц в виде числа с нулем в начале (01–31). Если (mm) следует после (h) или (hh), отображаются минуты.
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

Заливка ячейки цветом в VBA Excel

Пример кода 1:

Sub ColorTest1()

Range(“A1”).Interior.Color = 31569

Range(“A4:D8”).Interior.Color = 4569325

Range(“C12:D17”).Cells(4).Interior.Color = 568569

Cells(3, 6).Interior.Color = 12659

End Sub

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

Есть один интересный нюанс: если присвоить свойству .Interior.Color отрицательное значение от -16777215 до -1, то цвет будет соответствовать значению, равному сумме максимального значения палитры (16777215) и присвоенного отрицательного значения. Например, заливка всех трех ячеек после выполнения следующего кода будет одинакова:

Sub ColorTest11()

Cells(1, 1).Interior.Color = 12207890

Cells(2, 1).Interior.Color = 16777215 + (12207890)

Cells(3, 1).Interior.Color = 4569325

End Sub

Проверено в Excel 2016.

Создание новых стилей

Если встроенных стилей Excel не достаточно, то можно создать собственные стили. Это достаточно просто сделать:

  1. Выберите любую ячейку и отформатируйте ее обычным способом так как вам нравится. Форматирование этой ячейки в дальнейшим мы сохраним как именованный стиль. Вы можете использовать любое доступное форматирование из диалогового окна Форматирование ячеек.
  2. Перейдите на вкладку Главная -> Стили ячеек и выберите команду Создать стиль ячейки. Откроется диалоговое окно Стиль.
  3. Выберите Имя стиля, которое будет в дальнейшем будете использовать.
  4. Выберите опции, которые будут применяться к выбранному стилю (по умолчанию отмечены все опции). Если нет необходимости в какой то опции, например вы не хотите изменять шрифт ячейки – то снимите выбор.
  5. Нажмите кнопку OK.

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

Выравнивание по вертикали

Для выравнивания текста в ячейках рабочего листа по вертикали в VBA Excel используется свойство VerticalAlignment объекта Range. Оно может принимать следующие значения:

Выравнивание Константа Значение
По верхнему краю xlTop -4160
По центру xlCenter -4108
По нижнему краю xlBottom -4107

Точно так же, как и по горизонтали, при выравнивании по вертикали свойству VerticalAlignment можно присваивать как значение из константы, так и непосредственно ее числовое значение.

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

1

2

3

4

5

6

7

8

9

10

11

12

13

14

Sub Primer2()

‘Заполняем ячейки текстом

Range(“A3”) = “Верх”

Range(“B3”) = “Центр”

Range(“C3”) = “Низ”

‘Применяем вертикальное выравнивание

Range(“A3”).VerticalAlignment = xlTop

Range(“B3”).VerticalAlignment = xlCenter

Range(“C3”).VerticalAlignment = xlBottom

‘Выводим значения констант

Range(“A4”) = “xlTop = “ & xlTop

Range(“B4”) = “xlCenter = “ & xlCenter

Range(“C4”) = “xlBottom = “ & xlBottom

End Sub

Зачем нужны именованные стили

Идея именованных стилей заключается в следующем:

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

Стили Excel позволяют отформатировать следующие атрибуты:

  • числовой формат (например, число, короткий формат даты, формат телефонного номера и т.п.);
  • выравнивание (по вертикали и горизонтали);
  • шрифт (название, размер, цвет и пр.);
  • граница (тип линии, цвет границы);
  • заливка (цвет фона, узор);
  • защита (защищаемая ячейка, скрытие формул).

Описание VBA-макроса для формата ячеек таблицы Excel

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

  1. Текст в значениях ячеек выравнивается по центру горизонтально и вертикально.
  2. Включен построчный перенос текста.
  3. Все границы ячеек получают черную обычной толщины непрерывную линию с черным цветом.
  4. Сброс цвета шрифта на авто.
  5. Удаляется любая заливка ячеек.
  6. Ширина столбцов автоматически настраивается под текст в ячейках.
  7. Автоматически настроить высоту строк по содержимому ячеек.

Использование предопределенных констант

В VBA Excel есть предопределенные константы часто используемых цветов для заливки ячеек:

Предопределенная константа Наименование цвета
vbBlack Черный
vbBlue Голубой
vbCyan Бирюзовый
vbGreen Зеленый
vbMagenta Пурпурный
vbRed Красный
vbWhite Белый
vbYellow Желтый
xlNone Нет заливки

Присваивается цвет ячейке предопределенной константой в VBA Excel точно так же, как и числовым значением:

Пример кода 3:

Range(“A1”).Interior.Color = vbGreen

Изменение существующих стилей

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

  1. Перейти на вкладку Главная -> Стили ячеек.
  2. Щелкнуть правой кнопкой мыши по стилю, который хотите изменить и выбрать команду Изменить.
  3. Откроется диалоговое окно Стиль, в котором указано применяемое к ячейке форматирование.
  4. Нажмите на кнопку Формат, и в появившемся диалоговом окне Формат ячеек задайте необходимое форматирование. Например, чтобы изменить размер шрифта перейдите на вкладку Шрифт, задайте нужный размер и нажмите кнопку ОК.
  5. Нажмите еще раз кнопку ОК, чтобы закрыть окно Стиль и применить форматирование к изменяемому стилю.

Источники

  • https://vremya-ne-zhdet.ru/vba-excel/formatirovaniye-teksta-v-yacheyke/
  • https://micro-solution.ru/excel/formatting/formatting-styles
  • https://exceltable.com/vba-macros/makrosy-dlya-formatirovaniya-yacheek
  • https://vremya-ne-zhdet.ru/vba-excel/tsvet-yacheyki-zalivka-fon/
  • https://vremya-ne-zhdet.ru/vba-excel/vyravnivaniye-teksta-v-yacheyke/
  • https://vremya-ne-zhdet.ru/vba-excel/funktsiya-format/

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

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

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