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:
- xlDiagonalDown (Border running from the upper left-hand corner to the lower right of each cell in the range).
- xlDiagonalUp (Border running from the lower left-hand corner to the upper right of each cell in the range).
- xlEdgeBottom (Border at the bottom of the range).
- xlEdgeLeft (Border at the left-hand edge of the range).
- xlEdgeRight (Border at the right-hand edge of the range).
- xlEdgeTop (Border at the top of the range).
- xlInsideHorizontal (Horizontal borders for all cells in the range except borders on the outside of the range).
- 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:
- xlPatternAutomatic (Excel controls the pattern.)
- xlPatternChecker (Checkerboard.)
- xlPatternCrissCross (Criss-cross lines.)
- xlPatternDown (Dark diagonal lines running from the upper left to the lower right.)
- xlPatternGray16 (16% gray.)
- xlPatternGray25 (25% gray.)
- xlPatternGray50 (50% gray.)
- xlPatternGray75 (75% gray.)
- xlPatternGray8 (8% gray.)
- xlPatternGrid (Grid.)
- xlPatternHorizontal (Dark horizontal lines.)
- xlPatternLightDown (Light diagonal lines running from the upper left to the lower right.)
- xlPatternLightHorizontal (Light horizontal lines.)
- xlPatternLightUp (Light diagonal lines running from the lower left to the upper right.)
- xlPatternLightVertical (Light vertical bars.)
- xlPatternNone (No pattern.)
- xlPatternSemiGray75 (75% dark moiré.)
- xlPatternSolid (Solid color.)
- 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
Свойства ячейки, часто используемые в коде 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 тем, что оно предназначено только для чтения.
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:
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.
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")
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:
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:
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:
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):
VBA Coding Made Easy
Stop searching for VBA code online. Learn more about AutoMacro — A VBA Code Builder that allows beginners to code procedures from scratch with minimal coding knowledge and with many time-saving features for all users!
Learn More
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:
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:
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:
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 |
Содержание
- VBA Format Cells
- Formatting Cells
- AddIndent
- Borders
- FormulaHidden
- HorizontalAlignment
- VBA Coding Made Easy
- IndentLevel
- Interior
- Locked
- MergeCells
- NumberFormat
- NumberFormatLocal
- Orientation
- Parent
- ShrinkToFit
- VerticalAlignment
- WrapText
- VBA Code Examples Add-in
- Formatting Numbers in Excel VBA
- 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
- VBA Coding Made Easy
- 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
- VBA Code Examples Add-in
VBA Format Cells
In this Article
This tutorial will demonstrate how to format cells using VBA.
Formatting Cells
There are many formatting properties that can be set for a (range of) cells like this:
Let’s see them in alphabetical order:
AddIndent
By setting the value of this property to True the text will be automatically indented when the text alignment in the cell is set, either horizontally or vertically, to equal distribution (see HorizontalAlignment and VerticalAlignment).
Borders
You can set the border format of a cell. See here for more information about borders.
As an example you can set a red dashed line around cell B2 on Sheet 1 like this:
You can adjust the cell’s font format by setting the font name, style, size, color, adding underlines and or effects (strikethrough, sub- or superscript). See here for more information about cell fonts.
Here are some examples:
FormulaHidden
This property returns or sets a variant value that indicates if the formula will be hidden when the worksheet is protected. For example:
HorizontalAlignment
This property cell format property returns or sets a variant value that represents the horizontal alignment for the specified object. Returned or set constants can be: xlGeneral, xlCenter, xlDistributed, xlJustify, xlLeft, xlRight, xlFill, xlCenterAcrossSelection. For example:
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!
IndentLevel
It returns or sets an integer value between 0 and 15 that represents the indent level for the cell or range.
Interior
You can set or get returned information about the cell’s interior: its Color, ColorIndex, Pattern, PatternColor, PatternColorIndex, PatternThemeColor, PatternTintAndShade, ThemeColor, TintAndShade, like this:
Locked
This property returns True if the cell or range 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. It can be used also for locking or unlocking cells.
This example unlocks cells A1:B2 on Sheet1 so that they can be modified when the sheet is protected.
MergeCells
Set this property to True if you need to merge a range. Its value gets True if a specified range contains merged cells. For example, if you need to merge the range of C5:D7, you can use this code:
NumberFormat
You can set the number format within the cell(s) to General, Number, Currency, Accounting, Date, Time, Percentage, Fraction, Scientific, Text, Special and Custom.
Here are the examples of scientific and percentage number formats:
NumberFormatLocal
This property returns or sets a variant value that represents the format code for the object as a string in the language of the user.
Orientation
You can set (or get returned) the text orientation within the cell(s) by this property. Its value can be one of these constants: xlDownward, xlHorizontal, xlUpward, xlVertical or an integer value from –90 to 90 degrees.
Parent
This is a read-only property that returns the parent object of a specified object.
ShrinkToFit
This property returns or sets a variant value that indicates if text automatically shrinks to fit in the available column width.
VerticalAlignment
This property cell format property returns or sets a variant value that represents the vertical alignment for the specified object. Returned or set constants can be: xlCenter, xlDistributed, xlJustify, xlBottom, xlTop. For example:
WrapText
This property returns True if text is wrapped in all cells within the specified range, False if text is not wrapped in all cells within the specified range, or Null if the specified range contains some cells that wrap text and other cells that don’t.
For example, if you have this range of cells:
this code below will return Null in the Immediate Window:
VBA Code Examples Add-in
Easily access all of the code examples found on our site.
Simply navigate to the menu, click, and the code will be inserted directly into your module. .xlam add-in.
Источник
Formatting Numbers in Excel VBA
In this Article
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:
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.
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:
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:
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:
You clear this from the status bar by using:
Creating a Format String
This example will add the text ‘Total Sales’ after each number, as well as including a thousands separator
This is what your numbers will look like:
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
This will display your numbers as follows:
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:
This will produce the following results on your worksheet:
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:
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.
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
This will be the result using only one comma (divide by 1,000):
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!
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
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:
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:
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:
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:
This is the result that will be produced:
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
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:
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:
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.
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
The result will be 1234567.89
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
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
This displays the number with the thousand separators, but only to two decimal places.
The result will be 1,234,567.89
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
This converts the number to Exponential format
The result will be 1.23E+06
Yes/No
This displays ‘No’ if the number is zero, otherwise displays ‘Yes’
The result will be ‘Yes’
True/False
This displays ‘False’ if the number is zero, otherwise displays ‘True’
The result will be ‘True’
On/Off
This displays ‘Off’ if the number is zero, otherwise displays ‘On’
The result will be ‘On’
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
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
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’
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
Displays a long time as defined in Windows Control Panel (Clock and Region | Region).
The result will be ‘4:11:39 PM’
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
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’
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 |
VBA Code Examples Add-in
Easily access all of the code examples found on our site.
Simply navigate to the menu, click, and the code will be inserted directly into your module. .xlam add-in.
Источник
Содержание
- 1 Add & format totals
- 2 Change range border color
- 3 Change range border style
- 4 Changes color of numbers
- 5 Changes font to bold
- 6 Format current region
- 7 Format date on report
- 8 Formatting Range: Font
- 9 Formatting Range: HorizontalAlignment, VerticalAlignment, MergeCells
- 10 Line style: xlContinuous
- 11 Line style: xlDash
- 12 Line style: xlDashDot
- 13 Line style: xlDashDotDot
- 14 Line style: xlDot
- 15 Line style: xlDouble
- 16 Line style: xlLineStyleNone
- 17 Line style: xlSlantDashDot
- 18 Make column headings bold
- 19 Make text in first column bold
- 20 Providing Dynamic Scaling to Your Worksheets
- 21 Sets to True the Bold property of the Font object contained in the Range object
- 22 Set the color for whole range
- 23 Set the underline, color and font name
- 24 Specify colors with VBA»s RGB function.
- 25 Strolling Through the Color Palette
- 26 The Font property
- 27 The Interior property:changes the Color property of the Interior object contained in the Range object:
- 28 Use the Range and Cells properties of the Worksheet object to return a Range object.
- 29 Using the Interior Object to Alter the Background of a Range
- 30 Widen first column to display text
Add & format totals
<source lang="vb">
Sub RigidFormattingProcedure()
ActiveSheet.Range("N7:N15").Formula = "=SUM(RC[-12]:RC[-1])" ActiveSheet.Range("N7:N15").Font.Bold = True ActiveSheet.Range("B16:N16").Formula = "=SUM(R[-9]C:R[-1]C)" ActiveSheet.Range("B16:N16").Font.Bold = True
End Sub
" Format data range
Sub RigidFormattingProcedure()
ActiveSheet.Range("B7:N16").NumberFormat = "#,##0"
End Sub
</source>
Change range border color
<source lang="vb">
Sub BorderDemo()
With Range("A1:E5") .BorderAround ColorIndex:=1 End With
End Sub
</source>
Change range border style
<source lang="vb">
Sub Extend()
With Range("A1:E5") .Borders.LineStyle = xlLineStyleNone .Resize(.Rows.Count + 1).Name = "Database" End With
End Sub
</source>
Changes color of numbers
<source lang="vb">
Sub ColorCells1()
Dim myRange As Range Dim i As Long, j As Long Set myRange = Range("A1:A5") For i = 1 To myRange.Rows.Count For j = 1 To myRange.Columns.Count If myRange.Cells(i, j).Value < 100 Then myRange.Cells(i, j).Font.ColorIndex = 3 Else myRange.Cells(i, j).Font.ColorIndex = 1 End If Next j Next i
End Sub
</source>
Changes font to bold
<source lang="vb">
Sub Bold()
Dim rngRow As Range For Each rngRow In Range("A1:E5").Rows If rngRow.Cells(1).Value > 1 Then rngRow.Font.Bold = True Else rngRow.Font.Bold = False End If Next rngRow
End Sub
</source>
Format current region
<source lang="vb">
Sub FormatCurrentRegion()
Set WorkRange = ActiveCell.CurrentRegion WorkRange.Font.Bold = True
End Sub
</source>
Format date on report
<source lang="vb">
Sub RigidFormattingProcedure()
ActiveSheet.Range("A2").NumberFormat = "mmm-yy"
End Sub
</source>
Formatting Range: Font
<source lang="vb"> Sub InsertHeader() Range("A1:C1").Select With Selection.Font .Name = "Arial" .FontStyle = "Bold" .Size = 14 End With End Sub </source>
Formatting Range: HorizontalAlignment, VerticalAlignment, MergeCells
<source lang="vb"> Sub InsertHeader() Range("A1:C1").Select With Selection .HorizontalAlignment = xlGeneral .VerticalAlignment = xlBottom .MergeCells = True End With End Sub </source>
Line style: xlContinuous
<source lang="vb">
Sub BorderLineSytlesII()
Dim rg As Range Set rg = ThisWorkbook.Worksheets("Borders").Range("A1:E3") rg.Offset(1, 2).Borders(xlEdgeBottom).LineStyle = xlContinuous Set rg = Nothing
End Sub
</source>
Line style: xlDash
<source lang="vb">
Sub BorderLineSytlesII()
Dim rg As Range Set rg = ThisWorkbook.Worksheets("Borders").Range("A1:E3") rg.Offset(1, 2).Borders(xlEdgeBottom).LineStyle = xlDash Set rg = Nothing
End Sub
</source>
Line style: xlDashDot
<source lang="vb">
Sub BorderLineSytlesII()
Dim rg As Range Set rg = ThisWorkbook.Worksheets("Borders").Range("A1:E3") rg.Offset(1, 2).Borders(xlEdgeBottom).LineStyle = xlDashDot Set rg = Nothing
End Sub
</source>
Line style: xlDashDotDot
<source lang="vb">
Sub BorderLineSytlesII()
Dim rg As Range Set rg = ThisWorkbook.Worksheets("Borders").Range("A1:E3") rg.Offset(1, 2).Borders(xlEdgeBottom).LineStyle = xlDashDotDot Set rg = Nothing
End Sub
</source>
Line style: xlDot
<source lang="vb">
Sub BorderLineSytlesII()
Dim rg As Range Set rg = ThisWorkbook.Worksheets("Borders").Range("A1:E3") rg.Offset(1, 2).Borders(xlEdgeBottom).LineStyle = xlDot Set rg = Nothing
End Sub
</source>
Line style: xlDouble
<source lang="vb">
Sub BorderLineSytlesII()
Dim rg As Range Set rg = ThisWorkbook.Worksheets("Borders").Range("A1:E3") rg.Offset(1, 2).Borders(xlEdgeBottom).LineStyle = xlDouble Set rg = Nothing
End Sub
</source>
Line style: xlLineStyleNone
<source lang="vb">
Sub BorderLineSytlesII()
Dim rg As Range Set rg = ThisWorkbook.Worksheets("Borders").Range("A1:E3") rg.Offset(1, 2).Borders(xlEdgeBottom).LineStyle = xlLineStyleNone Set rg = Nothing
End Sub
</source>
Line style: xlSlantDashDot
<source lang="vb">
Sub BorderLineSytlesII()
Dim rg As Range Set rg = ThisWorkbook.Worksheets("Borders").Range("A1:E3") rg.Offset(1, 2).Borders(xlEdgeBottom).LineStyle = xlSlantDashDot Set rg = Nothing
End Sub
</source>
Make column headings bold
<source lang="vb">
Sub RigidFormattingProcedure()
ActiveSheet.Range("6:6").Font.Bold = True
End Sub
</source>
Make text in first column bold
<source lang="vb">
Sub RigidFormattingProcedure()
ActiveSheet.Range("A:A").Font.Bold = True
End Sub
</source>
Providing Dynamic Scaling to Your Worksheets
<source lang="vb">
Private Sub Worksheet_Change(ByVal Target As Range)
If Target.Address = Me.Range("ScaleFactor").Address Then ScaleData End If
End Sub
Private Sub ScaleData()
If Me.Range("ScaleFactor").Value = "Normal" Then Me.Range("ScaleRange").NumberFormat = "#,##0" Else Me.Range("ScaleRange").NumberFormat = "#," End If
End Sub
</source>
Sets to True the Bold property of the Font object contained in the Range object
<source lang="vb">
Sub bold()
range("A1").font.bold = True
End Sub
</source>
Set the color for whole range
<source lang="vb">
Sub ColorCells4()
Dim Rng As Range For Each Rng In Range("A1:E5") If Rng.Value < 100 Then Rng.Font.ColorIndex = 4 Else Rng.Font.ColorIndex = 1 End If Next Rng
End Sub
</source>
Set the underline, color and font name
<source lang="vb">
Sub DemonstrateFontObject()
Dim nColumn As Integer Dim nRow As Integer Dim avFonts As Variant Dim avColors As Variant avFonts = Array("Tahoma", "Arial", "MS Sans Serif", "Verdana", "Georgia") avColors = Array(vbRed, vbBlue, vbBlack, vbGreen, vbYellow) For nRow = 1 To 5 With ThisWorkbook.Worksheets(1).Rows(nRow).Font .Color = avColors(nRow - 1) .Name = avFonts(nRow - 1) If nRow Mod 2 = 0 Then .Underline = True Else .Underline = False End If End With Next
End Sub
</source>
Specify colors with VBA»s RGB function.
<source lang="vb">
Sub rgbDemo()
range("A1").Interior.color = rgb(0, 0, 0) "black range("A2").Interior.color = rgb(255, 0, 0) " pure red range("A3").Interior.color = rgb(0, 0, 255) " pure blue range("A4").Interior.color = rgb(128, 128, 128) " middle gray
End Sub
</source>
Strolling Through the Color Palette
<source lang="vb">
Sub ViewWorkbookColors()
Dim rg As Range Dim nIndex As Integer Set rg = ThisWorkbook.Worksheets("Sheet1").Range("A1:E5").Offset(1, 0) For nIndex = 1 To 56 rg.Value = nIndex rg.Offset(0, 1).Interior.ColorIndex = nIndex rg.Offset(0, 2).Value = rg.Offset(0, 1).Interior.Color Set rg = rg.Offset(1, 0) Next Set rg = Nothing
End Sub
</source>
The Font property
<source lang="vb">
Sub font()
Debug.Print range("A1").font.Background
End Sub
</source>
The Interior property:changes the Color property of the Interior object contained in the Range object:
<source lang="vb">
Sub color()
range("A1").Interior.color = 8421504
End Sub
</source>
Use the Range and Cells properties of the Worksheet object to return a Range object.
<source lang="vb">
Sub rangeColor()
Range("A:B").Font.Color = vbRed
End Sub
</source>
Using the Interior Object to Alter the Background of a Range
<source lang="vb">
Sub InteriorExample()
Dim rg As Range Set rg = ThisWorkbook.Worksheets("Sheet1").Range("A1").Offset(1, 0) Do Until IsEmpty(rg) rg.Offset(0, 2).Interior.Pattern = rg.Offset(0, 1).Value rg.Offset(0, 3).Interior.Pattern = rg.Offset(0, 1).Value rg.Offset(0, 3).Interior.PatternColor = vbRed Set rg = rg.Offset(1, 0) Loop " create examples of each VB defined color constant Set rg = ThisWorkbook.Worksheets("Sheet1").Range("A1:E3").Offset(1, 0) Do Until IsEmpty(rg) rg.Offset(0, 2).Interior.Color = rg.Offset(0, 1).Value Set rg = rg.Offset(1, 0) Loop Set rg = Nothing
End Sub
</source>
Widen first column to display text
<source lang="vb">
Sub RigidFormattingProcedure()
ActiveSheet.Range("A:A").EntireColumn.AutoFit
End Sub
</source>