Change format in excel vba

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

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

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

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

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

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

  • Expression – любое допустимое выражение (переменная), возвращающее числовое значение или строку (обязательный параметр).
  • FormatExpression – выражение формата, именованное или содержащее инструкции из специальных символов (необязательный параметр).
  • FirstDayOfWeek – константа, задающая первый день недели (необязательный параметр).
  • FirstWeekOfYear – константа, задающая первую неделю года (необязательный параметр).

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

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

Имя формата Описание
General Date Стандартное отображение даты и времени в соответствии с параметрами системы.
Long Date Длинный формат даты.
Medium Date Средний формат даты.
Short Date Краткий формат даты.
Long Time Длинный формат времени.
Medium Time Средний формат времени.
Short Time Краткий формат времени.

Проверьте отображение даты и времени с использованием именованных форматов на вашем компьютере при помощи следующего кода VBA Excel:

Sub FormatDateTime()

MsgBox «General Date:  « & Format(Now, «General Date») & vbNewLine _

& vbNewLine & «Long Date:  « & Format(Now, «Long Date») & vbNewLine _

& vbNewLine & «Medium Date:  « & Format(Now, «Medium Date») & vbNewLine _

& vbNewLine & «Short Date:  « & Format(Now, «Short Date») & vbNewLine _

& vbNewLine & «Long Time:  « & Format(Now, «Long Time») & vbNewLine _

& vbNewLine & «Medium Time:  « & Format(Now, «Medium Time») & vbNewLine _

& vbNewLine & «Short Time:  « & Format(Now, «Short Time»)

End Sub

Скорее всего, результат будет таким:

Отображение даты и времени в соответствии с именованными форматами

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

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

Проверяем работу именованных форматов на числах 2641387.7381962 и 0 с помощью кода VBA Excel:

Sub FormatNumber()

Dim n As Double

n = 2641387.7381962

‘n = 0

MsgBox «Форматируемое число = « & n & vbNewLine _

& vbNewLine & «General Number:  « & Format(n, «General Number») & vbNewLine _

& vbNewLine & «Currency:  « & Format(n, «Currency») & vbNewLine _

& vbNewLine & «Fixed:  « & Format(n, «Fixed») & vbNewLine _

& vbNewLine & «Standard:  « & Format(n, «Standard») & vbNewLine _

& vbNewLine & «Percent:  « & Format(n, «Percent») & vbNewLine _

& vbNewLine & «Scientific:  « & Format(n, «Scientific») & vbNewLine _

& vbNewLine & «Yes/No:  « & Format(n, «Yes/No») & vbNewLine _

& vbNewLine & «True/False:  « & Format(n, «True/False») & vbNewLine _

& vbNewLine & «On/Off:  « & Format(n, «On/Off»)

End Sub

Получаем следующий результат:

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

Вместо вопросительного знака в отображении числа в формате Currency, по идее, должен быть знак валюты (₽ или руб.).

Специальные символы для выражений форматов

Символы для форматов даты и времени

Символ Описание
Точка (.) Разделитель компонентов даты (день, месяц, год). Используется при отображении месяца в виде числа.
Пробел Разделитель компонентов даты (день, месяц, год). Используется при отображении месяца прописью.
Двоеточие (:) Разделитель компонентов времени (часы, минуты, секунды).
d День в виде числа без нуля в начале (1–31).
dd День в виде числа с нулем в начале (01–31).
m Месяц в виде числа без нуля в начале (1–12). Если (m) следует после (h) или (hh), отображаются минуты (0–59).
mm Месяц в виде числа с нулем в начале (01–12). Если (mm) следует после (h) или (hh), отображаются минуты (00–59).
mmm Месяц прописью в сокращенном виде (янв–дек).
mmmm Полное название месяца (январь–декабрь).
y День года в виде числа (1–366).
yy Год в виде 2-значного числа (00–99).
yyyy Год в виде 4-значного числа (1900–9999).
h Часы в виде числа без нуля в начале (0–23).
hh Часы в виде числа с нулем в начале (00–23).
n (m) Минуты в виде числа без нуля в начале (0–59).
nn (mm) Минуты в виде числа с нулем в начале (00–59).
s Секунды в виде числа без нуля в начале (0–59).
ss Секунды в виде числа с нулем в начале (00–59).

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

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

Sub DataIsD()

MsgBox «d:  « & Format(Now, «d») & vbNewLine _

& vbNewLine & «dd:  « & Format(Now, «dd») & vbNewLine _

& vbNewLine & «ddd:  « & Format(Now, «ddd») & vbNewLine _

& vbNewLine & «dddd:  « & Format(Now, «dddd») & vbNewLine _

& vbNewLine & «ddddd:  « & Format(Now, «ddddd») & vbNewLine _

& vbNewLine & «dddddd:  « & Format(Now, «dddddd»)

End Sub

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

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

Символ Описание
Точка (.) Десятичный разделитель.
Запятая (,) Разделитель групп разрядов. В отображаемых числах заполняется пробелом.
(0) Заполнитель, который отображает цифру или ноль. Используется, когда нужны ведущие нули или нули в конце числа.
(#) Заполнитель, который отображает цифру или ничего не отображает. Используется, когда не нужны ведущие нули или нули в конце числа.
(%) Заполнитель процента. Выражение умножается на 100, а знак процента (%) вставляется на той позиции, где он указан в строке формата.
(E- E+ e- e+) Экспоненциальный формат.

Примеры использования символов в выражениях числовых форматов VBA Excel:

Sub FormatNumber2()

Dim n As Double

n = 2641387.7381962

‘n = 0.2397842

MsgBox «Форматируемое число = « & n & vbNewLine _

& vbNewLine & «0.##:  « & Format(n, «0.##») & vbNewLine _

& vbNewLine & «000.###:  « & Format(n, «000.###») & vbNewLine _

& vbNewLine & «#,###.###:  « & Format(n, «#,###.###») & vbNewLine _

& vbNewLine & «0 %:  « & Format(n, «0 %») & vbNewLine _

& vbNewLine & «0.### E-:  « & Format(n, «0.### E-«) & vbNewLine _

& vbNewLine & «0.### E+:  « & Format(n, «0.### E+»)

End Sub

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

Символ Описание
At-символ (@) Заполнитель для символов, отображающий знак или пробел.
Амперсанд (&) Заполнитель для символов, отображающий знак или ничего (пустая строка).
Меньше (<) Принудительный перевод всех буквенных символов в нижний регистр.
Больше (>) Принудительный перевод всех буквенных символов в верхний регистр.

Примеры использования символов в выражениях строковых форматов VBA Excel:

Sub FormatString()

MsgBox «Номер телефона:  « & Format(«1234567890», «+7 (@@@) @@@-@@-@@») & vbNewLine _

& vbNewLine & «Серия и номер паспорта:  « & Format(«1234567890», «&& && &&&&») & vbNewLine _

& vbNewLine & «Нижний регистр:  « & Format(«Нижний регистр», «<«) & vbNewLine _

& vbNewLine & «Верхний регистр: « & Format(«Верхний регистр», «>»)

End Sub

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

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

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

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

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

Пример использования четырех разделов в выражении формата числовых значений:

Sub FormatDifferentValues()

MsgBox «Число 1234,5678:  « & _

Format(1234.5678, «#,##0.00 руб.;Отрицательное число;Ноль рублей;Значение Null») _

& vbNewLine & vbNewLine & «Число -25:  « & _

Format(25, «#,##0.00 руб.;Отрицательное число;Ноль рублей;Значение Null») _

& vbNewLine & vbNewLine & «Число 0:  « & _

Format(0, «#,##0.00 руб.;Отрицательное число;Ноль рублей;Значение Null») _

& vbNewLine & vbNewLine & «Null:  « & _

Format(Null, «#,##0.00 руб.;Отрицательное число;Ноль рублей;Значение Null»)

End Sub

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

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

Количество разделов Результат форматирования
Один раздел Выражение формата применяется ко всем строковым данным.
Два раздела Первый раздел применяется к строковым данным, второй – к значениям Null и пустым строкам («»).

Пример использования двух разделов в выражении формата строк:

Sub FormatString2()

MsgBox «Строка «Белка»:  « & _

Format(«Белка», «@;Пустая строка или Null») _

& vbNewLine & vbNewLine & «Пустая строка:  « & _

Format(«», «@;Пустая строка или Null») _

& vbNewLine & vbNewLine & «Строка «Null»:  « & _

Format(«Null», «@;Пустая строка или Null») _

& vbNewLine & vbNewLine & «Значение Null:  « & _

Format(Null, «@;Пустая строка или Null»)

End Sub

VBA Format Date

Excel VBA Format Date

In general, we have different types of Date formats that are used in all around the world but we mostly use the data in the DDMMYYYY format. For this, in VBA we have Format function which is quite popular for converting Format Date. The date or number which we feed in using the Format function converts that into the required format which we choose. Below we have the syntax of the FORMAT Function in VBA.

Syntax of FORMAT Function:

VBA Format Date Example

Where, Format = It is the type by which we want to see the format of a date.

We know and probably have used many types of Date formats in our life and most of the formats are so commonly used such as DDMMYYYY and MMDDYYYY. Where we have seen DDMMYYYY used mostly in India and MMDDYYYY is used globally. Also, there are different separators that are used in creating a date format such as hyphen, slash, dot, brackets, etc. In this article, we will see the ways to use format the date in upcoming examples.

How to Change Date Format in VBA Excel?

Below are the examples of the excel VBA date format:

You can download this VBA Format Date Excel Template here – VBA Format Date Excel Template

Example #1

In this example, we will see a simple VBA code to format the date. We have a date in cell A1 as 25-Jun-20 as shown below.

Now we will be using the Format Date function to change the format of date in cell A1.

VBA Format Date Example 1

Step 1: Insert a new module inside Visual Basic Editor (VBE). Click on Insert tab > select Module.

Insert Module

Step 2: Write the subprocedure for VBA Format Date or choose anything to define the module.

Code:

Sub VBA_FormatDate()

End Sub

VBA Format Date Example 1-1

Step 3: Choose the range cell first as A1.

Code:

Sub VBA_FormatDate()

Range("A1").

End Sub

Range Cell Example 1-2

Step 4: Then use the Number Format function as shown below.

Code:

Sub VBA_FormatDate()

Range("A1").NumberFormat =

End Sub

VBA Format Date Example 1-3

Step 5: As per the syntax of the Format function, choose the format by which we want to change the Date of the selected cell.

Code:

Sub VBA_FormatDate()

Range("A1").NumberFormat = "dd.mm.yy"

End Sub

VBA Format Date Example 1-4

Step 6: Run the code by pressing F5 or Play Button is mentioned below the menu bar. We will see the Date at cell A1 is now changed to DD.MM.YY and visible as 25.06.20.

VBA Format Date Example 1-5

Example #2

There is another way to change the Format of Date in VBA.

Step 1: For this again we would need a module and in that write the subprocedure for VBA Format Date.

Code:

Sub VBA_FormatDate1()

End Sub

Subprocedure Example 2-1

Step 2: Now using DIM declare a variable choosing the data type as a Variant. We have chosen Variant as it would allow most of the characters in it.

Code:

Sub VBA_FormatDate1()

Dim DD As Variant

End Sub

Declare Variable Example 2-2

Step 3: Put any number which we would like to see that converting into a date. Here we have chosen 43586 as shown below.

Code:

Sub VBA_FormatDate1()

Dim DD As Variant
DD = 43586

End Sub

VBA Format Date Example 2-3

Step 4: To see the output, here we will use the message box as shown below with the FORMAT function.

Code:

Sub VBA_FormatDate1()

Dim DD As Variant
DD = 43586
MsgBox Format(

End Sub

Message Box Example 2-4

Step 5: As per the syntax of the Format function, we will now use the DD variable and the format in which we want to convert the mentioned number into a date as shown below.

Code:

Sub VBA_FormatDate1()

Dim DD As Variant
DD = 43586
MsgBox Format(DD, "DD-MM-YYYY")

End Sub

VBA Format Date Example 2-5

Step 6: We will see in the message box, the Format function has converted it into 01-05-2019 as shown below.

VBA Format Date Example 2-6

Example #3

There is another way to convert a date’s format into another format as needed. For this, we will be using the same number which we have seen in the above example-1 as 44007 in cell A1.

VBA Format Date Example 3

Step 1: Open a module and in that write the subprocedure of VBA Format Date.

Code:

Sub VBA_FormatDate2()

End Sub

VBA Format Date Example 3-1

Step 2: Define a variable using DIM as Worksheet as shown below.

Code:

Sub VBA_FormatDate2()

Dim DD As Worksheet

End Sub

VBA Format Date Example 3-2

Step 3: Now using SET, choose the worksheet which we want to assign in the defined variable DD. Here, that worksheet is Sheet2.

Code:

Sub VBA_FormatDate2()

Dim DD As Worksheet
Set DD = ThisWorkbook.Sheets(2)

End Sub

VBA Format Date Example 3-4

Step 4: In a similar way as shown in example-1, we will Range cell A1 with defined variable DD and then insert the Number Format function as shown below.

Code:

Sub VBA_FormatDate2()

Dim DD As Worksheet
Set DD = ThisWorkbook.Sheets(2)
DD.Range("A1").NumberFormat =

End Sub

Range cell Example 3-5

Step 5: Now as needed, we will choose the Date format we want to see in the number at cell A1 as shown below.

Code:

Sub VBA_FormatDate2()

Dim DD As Worksheet
Set DD = ThisWorkbook.Sheets(2)
DD.Range("A1").NumberFormat = "dddd, mmmmdd, yyyy"

End Sub

VBA Format Date Example 3-5

Step 6: Once done, run the code to see the output in cell A1. We will see, as per chosen date format, cell A1 has the date as Thursday, June25, 2020.

VBA Format Date Example 3-6

Step 7: We are seeing the weekday name because as per the format we need to exclude that manually. We would insert the value as $-F800 to skip weekday.

Code:

Sub VBA_FormatDate2()

Dim DD As Worksheet
Set DD = ThisWorkbook.Sheets(2)
DD.Range("A1").NumberFormat = "[$-F800]dddd, mmmmdd, yyyy"

End Sub

VBA Format Date Example 3-7

Step 8: Now again run the code to see the required Date format. The new date format is now shown as 25 June 2020.

Date format Example 3-8

Pros of VBA Format Date

  • VBA Format Date is quite useful which helps us to see any kind of date format.
  • We can test and choose a variety of separators in VBA Format Date without any limit.

Things to Remember

  • We try to enter a date using any number, then we would get the default format which is there as per Operating System setting.
  • To see the number hidden in any date, we can first convert the date into number format and then try to use that number into the Format Date function.
  • We can only change the date format using the FORMAT function in any format we want.
  • We need to save the excel file after writing up the VBA Code in macro-enabled excel format to avoid losing the VBA code in the future.

Recommended Articles

This is a guide to the VBA Format Date. Here we discuss how to change the Date Format in VBA Excel along with practical examples and a downloadable excel template. You can also go through our other suggested articles –

  1. How to Use VBA Login?
  2. VBA Month | Examples With Excel Template
  3. How to Use Create Object Function in VBA Excel?
  4. How to Use VBA IsError Function?

Excel VBA Tutorial on how to set date formatsExcel provides you several options for formatting dates. In addition to the several built-in date formats that exist, you can create custom date formats.

Even though the process of manually applying a date format isn’t very complicated, there are some circumstances in which you may want to create macros that format dates. This may the case if, for example:

  • You use a particular date format constantly and want to be able to apply such a format without having to do everything manually; or
  • You frequently format cells or cell ranges in a particular way, and the formatting rules you apply include date formats.

Regardless of your situation, if you’re interested in understanding how you can use Visual Basic for Applications for purposes of formatting dates, you’ve found the right place.

When working in Visual Basic for Applications, there are a few different properties and functions you can use for purposes of formatting a date. The following 3 are commonly used:

  • The Format VBA function.
  • The Range.NumberFormatLocal property.
  • The Range.NumberFormat property.

This particular Excel tutorial focuses on the last item of the list above (the Range.NumberFormat property). I may cover the Format function and Range.NumberFormatLocal property in future blog posts. If you want to be informed whenever I publish new content in Power Spreadsheets, please make sure to register for our Newsletter by entering your email address below.

In addition to explaining the Range.NumberFormat property, I explain the different date format codes you can use and present 25 date formatting examples using VBA.

You can use the following detailed table of contents to navigate to the section of this tutorial that interests you the most.

Before I introduce the NumberFormat property in more detail, let’s start by taking a look at the sample file that accompanies this Excel tutorial:

Format Dates Using Excel VBA: Example

For purpose of this Excel tutorial, I use an Excel workbook that contains the full match schedule of the 2014 Brazil World Cup.

Sample table with dates to format

This Excel VBA Date Format Tutorial is accompanied by an Excel workbook containing the data and some versions of the macros I explain below. You can get immediate free access to this example workbook by subscribing to the Power Spreadsheets Newsletter.

Notice how the first column of the table contains dates:

Dates to format in Excel using VBA

These are the dates that I format throughout this tutorial.

However, since the focus of this macro is in formatting dates using VBA, we need a Sub procedure. The following image shows the basic structure of the macro (called “Format_Dates”) that I use to format these dates.

VBA code example to format date

The macro has a single statement:

Selection.NumberFormat = “m/d/yy;@”

Therefore, before I start showing examples of how you can format dates using VBA, let’s analyze this statement. For these purposes, you simply need to understand…

The Range.NumberFormat Property And How To Format An Excel Date Using VBA

As mentioned at the beginning of this Excel tutorial, you can generally use the Range.NumberFormat property to format dates.

The Range.NumberFormat property sets a Variant value. This value represents the number format code of the relevant Range object. For these purposes, the Range object is generally a single cell or a range of cells.

Strictly speaking, in addition to setting the NumberFormat property value, you can also return the property’s current setting. As explained by Excel authority John Walkenbach in Excel VBA Programming for Dummies, the NumberFormat property is a read-write property.

However, if you’re reading this Excel tutorial, you likely want to modify the property, not read it. Therefore, this guide focuses on how to change the NumberFormat property, not how to read it.

You can, however, easily examine the number format of a cell or range of cells. I explain how you can read a property value in this tutorial. In such cases, if (i) you select a range of cells and (ii) all the cells don’t share the same format, the Range.NumberFormat property returns Null.

NumberFormat is just one of the many (almost 100 by my count) properties of the Range object. As explained in Excel Macros for Dummies, once you’ve selected a range of cells (as the sample Format_Dates macro does), “you can use any of the Range properties to manipulate the cells”.

This Excel tutorial is quite specific. The only property of the Range object that I cover in this blog post is NumberFormat. In fact, I only explain (in high detail) one of the applications of the NumberFormat property: to format dates with VBA.

I may cover other properties of the Range object, or other applications of the NumberFormat property, in future tutorials. If you want to receive an email whenever I publish new material in Power Spreadsheets, please make sure to subscribe to our Newsletter by entering your email address below:

Syntax Of The Range.NumberFormat Property

The syntax of the Range.NumberFormat property is relatively simple:

expression.NumberFormat

In this case, “expression” stands for the Range object, or a variable that represents this object.

The sample Format_Dates macro shown above uses the Application.Selection property, which returns whichever object is selected. Generally, you can use the sample Format_Dates macro framework whenever the selection is a range of cells. Therefore, the sample macro uses the following version of the syntax above:

Selection.NumberFormat

You can use another expression instead of Selection. What matters, as I mention above, is that the expression stands for a Range object.

Whenever you want to modify the value of a property, you must do the following:

  • #1: Determine whether the property you’re working with uses arguments and, if that’s the case, determine what is the argument you want to use. These arguments are the ones that specify the value that the property takes.
  • #2: Use an equal sign to separate the property name from the property value.

As shown in the examples throughout this tutorial, if you’re implementing the NumberFormat property using the framework structure of the sample Format_Dates macro, argument values are generally surrounded by double quotes (” “).

Therefore, if you’re setting the NumberFormat property value, you can use the following syntax:

expression.NumberFormat = “argument_value”

In other words, in order to change the current setting of the NumberFormat property, you use a statement including the following 3 items:

  • Item #1: A reference to the NumberFormat property.
  • Item #2: The equal sign (=).
  • Item #3: The new value of the NumberFormat property, surrounded by double quotes (” “).

As I explain above, the Range.NumberFormat property determines the number format code of a Range object. Therefore, in order to be able to format a date using VBA, you must understand…

Date Format Codes: The Arguments Of The Range.NumberFormat Property

As explained at the Microsoft Dev Center:

The format code is the same string as the Format Codes option in the Format Cells dialog box.

This is quite a mouthful, so let’s break down the statement and process into different parts to understand how you can know which format code you want to apply. More precisely, you can find the string that represents a particular format code in the Format Cells dialog box in the following 5 easy steps.

This process is, mostly, useful if you don’t know the format code you want to apply. Generally, as you become more familiar with number format codes, you’ll be able to create macros that format dates without having to go through this every time. For these purposes, refer to the introduction to date format codes below.

Step #1: Go To The Number Tab Of The Format Cells Dialog Box

You can get to the Format Cells dialog box using any of the following methods:

  • Method #1: Click on the dialog box launcher at the bottom-right corner of the Number command group of the Home Ribbon tab.

    Number dialog box in Excel

  • Method #2: Go to the Home tab of the Ribbon, expand the Number Format drop-down list and select More Number Formats.

    More Number Formats command

  • Method #3: Use the “Ctrl + 1” keyboard shortcut.

Regardless of which of the methods above you use, Excel displays the Format Cells dialog box.

Screenshot of Format Cells dialog in Excel

If you use method #1 or #2 above, Excel displays the Number tab, as in the image above. This is the one you need in order to find the date format codes.

However, if you use method #3 (keyboard shortcut), Excel may show you a tab other than the Number tab (as shown above). In such a case, simply go to the Number tab.

How to go to Number tab in Format Cells dialog

Step #2: Select The Date Category

Since you’re interested in date format codes, choose “Date” in the Category list box on the left side of the Format Cells dialog box.

Excel Date number category in dialog box

Step #3: Choose The Date Format Type Whose Format Code You Want

Once you’ve selected the Date category, Excel displays the built-in date format types inside the Type box on the right side of the Format Cells dialog box. This allows you to select from several different date format types.

For example, in the image above, I select the option “14-Mar-12”:

Format Cells example of date format type

Step #4: Select The Custom Category

Once you’ve selected the date format type you’re interested in, click on “Custom” within the Category list box on the right side of the Format Cells dialog.

Custom number formats in Excel Format Cells dialog box

Step #5: Get The Date Format Code

Once you’ve completed the 4 steps above, Excel displays the date format code that corresponds to the date format type you selected in step #3 above. This format code is shown in the Type box that appears on the upper-right section of the Format Cells dialog box.

Example of format date custom code in Excel

The date format code shown in the example above, is “[$-en-US]d-mmm-yy;@”. This format code corresponds to the option “14-Mar-12” with the English (United States) locale that I selected in step #3.

Once you have this date format code, you can go back to you VBA code and use this as the argument for the Range.NumberFormat property.

To see how this works in practice, let’s go back to the World Cup calendar that I introduce above. If you want to apply the format shown above, the VBA code looks as follows:

VBA macro to format date as d-mm-yy

As I show below, you can achieve the same date formatting effect without the first part of the date format code which makes reference to the locale settings. That means you can delete “[$-en-US]”. However, for the moment, I leave it in.

For purposes of this example, I modify the format of the dates that appear in the sample table. Let’s assume that, before applying this new version of the Format_Dates macro, all of the dates have the long date format, as shown in the following screenshot:

Long date format screenshot in Excel

Before executing the Format_Dates macro, I select the cell that I want to format. In this case, I choose the date in the first row of the table. This corresponds to June 12 of 2014, which is the date of the match between Brazil and Croatia.

Long date format example in Excel

Once I execute the version above of the Format_Dates macro, the date format changes to the following:

Example of date formatted with VBA

The 5-step method to find date format codes described above can be useful in some situations.

However, Excel date format codes follow some general rules. If you know them, you don’t have to go through the whole process described above every single time you want to create a macro that formats dates.

Let’s take a look at these general rules and some additional examples:

Date Format Codes In Excel And VBA: General Guidelines

The date format codes that you can use to format a date using VBA appear in the table below. As shown in the following sections, you can use these codes to create different types of date formats to use in your VBA code.

Format Code Applies To Format Code Description How It Looks In Practice
Month m Month is displayed as number.

It doesn’t include a leading 0.

1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12
Month mm Displays month as a number.

If the month is between January (month 1) and September (month 9), it includes a leading 0.

01, 02, 03, 04, 05, 06, 07, 08, 09, 10, 11, 12
Month mmm Month name is abbreviated. Jan, Feb, Mar, Apr, May, Jun, Jul, Aug, Sep, Oct, Nov, Dec
Month mmmm Full name of month is displayed January, February, March, April, May, June, July, August, September, October, November, December
Month mmmmm Only the first letter of the month name is displayed J, F, M, A, M, J, J, A, S, O, N, D
Day (Number) d The day number is displayed without a leading 0. 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
Day (Number) dd The day number is displayed.

For days between 1 and 9, a leading 0 is displayed.

01, 02, 03, 04, 05, 06, 07, 08, 09, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31
Day (Weekday) ddd The weekday is abbreviated Mon, Tue, Wed, Thu, Fri, Sat, Sun
Day (Weekday) dddd The full weekday name is displayed Monday, Tuesday, Wednesday, Thursday, Friday, Saturday, Sunday
Year yy The last 2 digits of the year are displayed 00 to 99
Year yyyy All of the four digits of the year are displayed 1900 to 9999

Note, however, that the Format function (which I mention at the beginning of this Excel tutorial) supports slightly different date format codes from those appear in this table.

The following sections show examples of how all of these different options can be applied to format dates using VBA. For each situation, I show both of the following:

  • The VBA code of the sample Format_Dates macro.
  • The resulting format in one of the dates within the sample table that contains the 2014 Brazil World Cup schedule.

Let’s start taking a look at each of these:

Format Date Using VBA: Display A Single Item Of The Date

You can have Excel display just one of the items of a date, regardless of whether it’s the month, the day or the year. To do this, the argument of the Range.NumberFormat property must only include the format code of the relevant item.

Let’s take a look at the different date formats you can obtain by including a single item, and how does the corresponding VBA code looks like:

Format A Date To Display Only The Month Using VBA

You can display a month using any of the following 5 options:

Option #1: Display The Month As A Number (Without Leading 0)

You can format a date in a way that:

  • Only the month is displayed; and
  • The month is displayed as a number without a leading 0.

In this case, the format code that you use as argument for the NumberFormat property is “m”. The image shows the version of the sample Format_Dates macro that does this:

VBA code example format date as m

Let’s go back to the sample table with the schedule of the 2014 World Cup. I select the second date, which is June 13 of 2014 and corresponds to the match between Mexico and Cameroon.

Excel date before formatting with VBA

The following image shows the results after the date is formatted by the Format_Dates macro. Notice how only the month number (6, corresponding to June) appears. Notice, also, that the value in the Formula Bar continues to be the same. The only thing that changes is the format of the date displayed in the cell itself.

Date formatted in Excel as m

Option #2: Display The Month As A Number (With Leading 0)

This option is similar to the one above. More particularly:

  • Only the month is displayed; and
  • The month is displayed as a number.

However, in this particular case, the month is displayed with a leading 0. In other words, if the relevant month is between January (month 01) and September (month 09), a leading 0 is added.

For these purposes, the VBA code behind the Format_Dates macro looks as follows:

Example of VBA code to format date as mm

This particular macro is applied to the third date in the 2014 World Cup schedule. The date is June 13 of 2014. The teams playing are Spain and Netherlands.

Date before executing date-formatting macro

Once the Format_Dates macro is applied, the date looks as follows in the cell (where the format changes) and the Formula Bar (where the value remains the same):

Excel date formatted as mm with VBA

Option #3: Display The Month As A 3-Letter Abbreviation

If you choose to implement this option, the month name is displayed as a 3-letter abbreviation. In order to achieve this, the VBA code of the Format_Dates macro is as follows:

VBA code to format date as mmm

Let’s continue with the same process of applying the new date formats to the match dates of the 2014 Brazil World Cup. In this case, the relevant date is June 13 of 2014. The match played is between Chile and Australia.

Excel date before formatting by macro

The following image shows how the cell looks like after the new format is applied. As in the previous cases, the value of the date itself (as shown in the Formula Bar), doesn’t change.

Example of date format mmm with VBA

Option #4: Display The Full Name Of The Month

If you want to display the full name of the month that corresponds to a date (not just its abbreviation), the following version of the Format_Dates macro is of help:

VBA code to format date as mmmm

In order to apply this format to a date in the sample 2014 Brazil World Cup schedule, I select the corresponding cell. In this case, the date is June 14 of 2014 and corresponds to the match between Colombia and Greece.

Excel date before mmmm formatting

The results of applying the new version of the Format_Dates macro are shown in the following screenshot:

Excel date with mmmm format from VBA

Option #5: Display The First Letter Of The Month

The fifth way in which you can display just the month when formatting a date using VBA is to display (only) the first letter of the relevant month. In this case, the Format_Dates macro looks as follows:

VBA code to display first day of month name

This macro is applied to the date June 14 of 2014. This date corresponds to the match between Uruguay and Costa Rica.

Date before being formatted in Excel

The results of executing the new macro are shown in the following image:

Date formatted using VBA to display first letter of month

Format A Date To Display Only The Day Number Using VBA

Just as you can use VBA to format a date in a way that only the month is displayed, you can do the same for the day. In other words, you can use Visual Basic for Applications to format a date and have Excel display only the day.

The following 2 sections show how you can modify the sample Format_Dates macro so that only the day (number) is displayed when the date is formatted.

Option #1: Display The Day Number Without Leading 0

If you want Excel to display the day number without a leading 0 while using VBA, you can use the following version of the sample Format_Dates macro:

VBA code to format date as d

The date to which this macro is applied in the sample workbook is June 14 of 2014. In this case, the relevant match is that between England and Italy.

Table with dates before formatting

The results of applying the Format_Dates macro are shown in the following image:

Excel date formatted as d by VBA

Option #2: Display The Day Number With Leading 0

You can format dates in such a way that Excel adds a leading 0 whenever the day is only 1 digit long (1 to 9). The following version of the Format_Dates macro achieves this:

VBA code sample to format date as dd

If I continue going down the 2014 Brazil World Cup match schedule (as until now), this version of the Format_Dates macro would be applied to the date June 14 of 2014. This date corresponds to the match between Ivory Coast and Japan.

Excel sample dates before VBA formatting

However, since this the day (14) doesn’t require a leading 0, the result of applying the new version of the Format_Dates macro would be the same as that obtained above for the date of the match between England and Italy.

Excel date formatted by VBA as dd

To see how this date format works like whenever the corresponding day is only one digit long, I go further down the sample table to one of the matches played at the beginning of July of 2014. More precisely, I apply the current version of the Format_Dates macro to the date July 1 of 2014. The match to which this date corresponds to is that played between Argentina and Switzerland.

Excel dates before VBA formatting

The following image shows the results of applying the Format_Dates macro to this date. Notice how, now, Excel adds a leading 0 to the day number in the cell.

Excel date formatted as dd with leading 0 using VBA

Format A Date To Display Only The Weekday Using VBA

The previous section shows how you can use VBA to format a date in such a way that only the day number is displayed. You can also format a date in such a way that only the weekday is displayed.

The following 2 sections show 2 ways in which you can implement this date format by using VBA.

Option #1: Display The Weekday As A 3-Letter Abbreviation

The first way in which you can format a date to display the weekday allows you to have that weekday shown as a 3-letter abbreviation. The following version of the Format_Dates macro achieves this:

VBA code that formats date as ddd

Let’s go back to the match between Ivory Coast and Japan to which I make reference above and apply this new date format. The date of this match is June 14 of 2014.

Excel dates before formatting with macro

After executing the Format_Dates macro, the date looks as follows:

Excel date formatted as ddd by format-dates macro

Option #2: Display The Full Weekday

The second way in which you can format a date to display the weekday using VBA makes Excel show the full name of the weekday. The following version of the sample Format_Dates macro formats a date in such a way:

VBA code sample to format date as dddd

Let’s execute this macro for purposes of formatting the date of the match between Switzerland and Ecuador in the 2014 Brazil World Cup match schedule. This date, as shown in the image below, is June 15 of 2014.

Excel date before VBA formatting

Running the Format_Dates macro while this particular cell is active causes the following change in the date format:

Excel date with dddd formatting by VBA

Format A Date To Display Only The Year Using VBA

So far, you have seen how you can format a date using VBA for purposes of displaying only the (i) month, (ii) day number or (iii) weekday. In this section, I show you how to format a date using VBA to display only the year.

Let’s take a look at the 2 options you have for these purposes:

Option #1: Display The Last 2 Digits Of The Year

The first way in which you can format a date to display only the year results in Excel displaying only the last 2 digits of the relevant year. To achieve this date format, you can use the following version of the Format_Dates macro:

VBA code example formats dates as yy

This date format is to applied to the date June 15 of 2014. This corresponds to the World Cup match between France and Honduras.

Excel date before being formatted by macro

The following image shows the results of executing the sample Format_Dates macro while this cell is active:

Excel date with yy format applied using VBA

Option #2: Display The Full Year

The second way in which you can format a date to display only the year results in Excel showing the full year. If you want to format a date in such a way using VBA, the following version of the Format_Dates macro achieves this result:

VBA code to format date and display full year

I apply this date format to the date of the match between Argentina and Bosnia and Herzegovina. This is June 15 of 2014.

Excel date not formatted by macro

Once the Format_Dates macro is executed, the results are as shown in the following screenshot:

Excel date after macro formats as yyyy

Format Date Using VBA: Display Several Items Of The Date

The examples in the section above explain different ways in which you can format a date using VBA to display a single item (month, day or year) of that particular date.

Having the ability to format a date in such a way that only a single item is displayed is helpful in certain scenarios. Additionally, once you know the format codes that apply to each of the individual items of a date, you can easily start combining them for purposes of creating more complex and advanced date formats.

In any case, in a lot of cases, you’ll need to format dates in such a way that more than 1 element is displayed. In the following sections, I go through some date formats that result in Excel displaying more than 1 item of the relevant date.

Even though I don’t cover every single date format that you can possibly implement, these examples give you an idea of the possibilities you have at your disposal and how you can implement them in your VBA code.

All of the sections below follow the same form and show 2 things:

  • The version of the Format_Dates macro that is applied.
  • The result of executing that macro for purposes of formatting 1 of the dates of a match in the sample workbook that accompanies this blog post.

Format Date Using VBA: Display m/d/yyyy

The following version of the Format_Dates macro formats a date in the form m/d/yyyy.

VBA code example to format date in form m/d/yyyy

The following image shows the result of applying this format to the date June 16 of 2014. This date corresponds to the match between Germany and Portugal.

Excel date with m/d/yyyy formatting by macro

Format Date Using VBA: Display m/d

To display a date in the form m/d, you can use the following macro:

VBA code example to format date as m/d

When this macro is executed and the cell with the date of the match between Iran and Nigeria (June 16 of 2014) is selected, the formatted date looks as follows:

Excel date with m/d format with VBA

Format Date Using VBA: Display m/d/yy

The following macro formats a date so that it’s displayed in the form m/d/yy:

VBA code example to format date in m/d/yy form

The result of applying this format, using the version of the Format_Dates macro above, to the date of June 16 of 2014 (for the match between Ghana and the USA) is shown below:

Date formatted in Excel as m/d/yy with VBA

Format Date Using VBA: Display mm/dd/yy

You can format a date so that it’s displayed in the form mm/dd/yy by using the following version of the Format_Dates macro:

VBA code formats date as mm/dd/yy

When this date format applied to the date of the World Cup match between Belgium and Algeria (June 17 of 2014), the result is as shown in the following image:

Excel date with mm/dd/yy format with VBA

Format Date Using VBA: Display d-mmm

The following version of the Format_Dates macro makes Excel display the date in the form d-mmm:

VBA code example to format date as d-mmm

The results of executing this macro while the date of the World Cup match between Brazil and Mexico is selected (June 17 of 2014) are shown in the next image:

Date formatted as d-mmm by VBA

Format Date Using VBA: Display d-mmm-yy

The next version of the Format_Dates macro makes Excel display dates using the form d-mmm-yy:

VBA code formatting date to d-mmm-yy

If I choose the cell that shows the date of the match between Russia and Korea (June 17 of 2014) prior to executing this version of the Format_Dates macro, the resulting date format is as follows:

Excel date with d-mmm-yy macro by VBA

Format Date Using VBA: Display dd-mmm-yy

To apply the format dd-mmm-yy to a particular date, you can use the following version of the sample Format_Dates macro:

VBA code sample to format date as dd-mmm-yy

The following screenshot shows the results of applying this version of the Format_Dates macro to the date in which Australia played against the Netherlands in the 2014 Brazil World Cup (June 18 of 2014):

Excel screenshot with date formatted by macro as dd-mmm-yy

Notice that, in this particular case, the resulting date format is exactly the same as that of the date of the match between Russia and Korea which is immediately above (and is used as an example in the previous section). To understand why this is the case, let’s take a look at the date format codes used in each case:

  • Russia vs. Korea (June 17 of 2014) uses the date format code d-mmm-yy.
  • Australia vs. Netherlands (June 18 of 2014) has the date format code dd-mmm-yy.

Notice that the only difference between both format codes is in the way the day is represented. In the first case, the format code uses “d”, which displays the day number without a leading 0. In the second case, the format code is “dd”, which adds a leading 0 whenever the day number has a single digit (between 1 and 9).

In this particular situation, the day numbers of both dates (17 and 18) have 2 digits. Therefore, the format code “dd” doesn’t add a leading 0 to the day number. The result is that shown above:

Both format codes (d-mmm-yy and dd-mmm-yy) result in the same date format when the number of digits of the day is 2 (between 10 and 31).

Let’s go further down the match schedule of the 2014 Brazil World Cup to see how the format code “dd-mmm-yy” adds a leading 0 when applied to a date in which the day number has a single digit:

The image below shows this. In this particular case, the Format_Dates macro is applied to the date July 1 of 2014, when Belgium played against the USA. Notice, especially, the leading 0 in the day number (01 instead of 1).

Example of Excel date format dd-mmm-yy using VBA

Format Date Using VBA: mmm-yy

The following version of the Format_Dates macro allows you to format a date using the form mmm-yy:

VBA code example formats dates in form mmm-yy

The resulting date format when this version of the Format_Date macro is executed is as shown in the image below. The formatted date is June 18 of 2014, corresponding to the match between Spain and Chile.

Excel screenshot with mmm-yy date format from VBA

Format Date Using VBA: mmmm-yy

Continuing with date formats that only display the month and year, the following version of the Format_Dates macro applies the format code mmmm-yy:

Example of VBA code that formats dates as mmmm-yy

The results of executing the macro on the date June 18 of 2014 are shown in the image below. In this case, the date corresponds to the World Cup match between Cameroon and Croatia.

Date formatted with VBA as mmmm-yy

Format Date Using VBA: mmmm d, yyyy

The following version of the sample Format_Dates macro formats dates so that they’re displayed using the form mmmm d, yyyy.

VBA code formatting dates as mmmm d, yyyy

The next image shows the results of executing this macro while a cell with the date June 19 of 2014 is active. This date corresponds to the world cup match between Colombia and Ivory Coast.

Excel date with VBA formatting as mmm d, yyyy

Format Date Using VBA: mmmmm-yy

The following version of the sample Format_Dates macro makes Excel display dates using the format mmmmm-yy.

VBA code to format date as mmmmm-yy

To see how a date looks like when formatted by this version of the Format_Dates macro, let’s go back to the 2014 Brazil World Cup match schedule. The following screenshot shows how the date June 19 of 2014 (for the match between Uruguay and England) looks like after this macro is executed:

Excel date with mmmmm-yy format from VBA

Format Date Using VBA: d-mmm-yyyy

Further above, I show versions of the Format_Dates macro that use the format codes d-mmm-yy and dd-mmm-yy. The version of this macro displayed in the image below results in a similar date format. The main difference between this version and those displayed above is that the version below displays the 4 digits of the year.

Example of VBA code to format dates as d-mmm-yyyy

I execute this macro while the cell with the date of the World Cup match between Japan and Greece (June 19 of 2014) is selected. The resulting date format is displayed in the image below:

Excel date formatted as d-mmm-yyy by VBA

Format Date Using VBA: dddd, mmmm dd, yyyy

The following version of the sample Format_Dates macro makes Excel display dates using the default long date format under the English (United States) locale settings.

VBA code to apply Excel long date format

To see how this looks in practice, check out the following image. This screenshot shows the date of the match between Italy and Costa Rica (June 20 of 2014) after the Format_Dates macro has been executed:

Excel date formatted with VBA to show long date

So far, this Excel tutorial includes 24 different examples of how you can use Visual Basic for Applications to format dates. The date formats introduced in the previous sections are relatively straightforward.

These basic date formats include several of the most commonly used date formats in American English. You can also use them as a basis to create other date formatting macros for less common date formats.

These basic date formats are, however, not the only ones you can apply. More precisely, once you have a good knowledge of how to apply date formats using VBA, you can start creating more complex constructions.

To finish this blog post, I introduce one such date formatting macro:

Format Date Using VBA: Add A Carriage Return To Dates

You can add a carriage return in custom date formats. This allows you to display different items of a date in different lines within a single cell.

Let’s see how this looks in practice:

The following screenshot shows an example of a date format with carriage returns. The formatted date is June 20 of 2014, corresponding to the World Cup match between Switzerland and France.

Example of Excel date format with carriage return

This example works with a date format that only includes month (using the format code mmmm) and year (using the format code yyyy). You can tweak the macro that I introduce below in order to adjust it to your needs and use any other date items or formats.

You can use Visual Basic for Applications for these purposes. The following macro (called “Format_Dates_Carriage_Return”) is the one that I’ve used to achieve the date format shown in the image above.

VBA code formats dates with carriage return

Some of the elements in this piece of VBA code probably look familiar. The following screenshot shows the elements that I introduce in the previous sections of this Excel tutorial:

VBA code to format date with previously explained sections

There are, however, a few other elements that I don’t introduce in the previous sections of this blog post. These are the following 5:

Element #1: With Statement

You can generally identify a With statement because of its basic syntax. This syntax is roughly as follows:

  • Begins with a statement of the form “With object”.

    In the case of the Format_Dates_Carriage_Return macro, this opening statement is “With Selection”. As explained above, the Application.Selection property returns the object that is currently selected. When formatting dates using the sample macro above (Format_Dates_Carriage_Return), the selected object is a range of cells.

    With statement within date-formatting macro

  • Has 1 or more statements in its body.

    You can easily identify these 2 statements within the Format_Dates_Carriage_Return macro due to the fact that they’re indented.

    With...End With block in VBA

  • Closes with an End With statement.

    Example of End With statement in VBA

The effect of using a With statement is that all of the statements within it refer to the same object or structure. In this case:

  • The object to which all of the statements refer to is that returned by the Selection property.
  • The statements that refer to the object returned by Selection are:

    Statement #1: .NumberFormat = “mmmm” & Chr(10) & “yyyy”.

    Statement #2: .RowHeight = .RowHeight * 2.

    Statement #3: .WrapText = True.

    I explain each of these statements below.

Using the With statement allows you to, among other, simplify the syntax of the macro. I use this statement in other sample macros throughout Power Spreadsheets, including macros that delete blank rows.

Element #2: The Ampersand (&) Operator

The first statement within the With…End With block is:

.NumberFormat = “mmmm” & Chr(10) & “yyyy”

Since, as explained above, this statement works with the object returned by the Application.Selection property, it’s the equivalent of:

Selection.NumberFormat = “mmmm” & Chr(10) & “yyyy”

Most of this statement follows exactly the same structure of (pretty much) all of the other macro examples I include in the previous sections. There are, however, a couple of new elements.

One of those new elements is the ampersand (&) operator. Notice how there are 2 ampersands (&) within this statement:

Ampersand in VBA code to format date

Within the Visual Basic for Applications environment, the ampersand (&) operator works in a very similar way to how it works in Excel itself.

This means that, within VBA, ampersand (&) is a concatenation operator. In other words, within the Format_Dates_Carriage_Return macro, ampersand (&) concatenates the 3 following expressions:

  • Expression #1: “mmmm”.
  • Expression #2: Chr(10).
  • Expression #3: “yyyy”.

Expression #2 above leads me to the next and last element you need to be aware of in order to understand the first statement within the With…End With block of the sample macro:

Element #3: The Chr Function

The Chr Function returns a string. The string that is returned is determined by the particular character code that you feed as an argument.

In the sample Format_Dates_Carriage_Return macro, the character code is the number 10. This corresponds to a linefeed character. In other words:

“Chr(10)” is what actually adds the carriage return between the date’s month and year.

The second statement within the With…End With block is also new. Let’s take a look at the new element it introduces:

Element #4: Range.RowHeight Property

The Range.RowHeight property allows you to set the height for a row.

In the Format_Dates_Carriage_Return sample macro, this property is used for purposes of doubling the height of the row for which you’re changing the date format. This is done by the statement:

.RowHeight = .RowHeight * 2

The expression to the right side of the equal sign (=) takes the current row height and, using the asterisk (*) operator, multiplies it by 2. The result of applying this property change to the sample chart with the 2014 Brazil World Cup Match Schedule is that a row can now fit the 2 date elements that are separated by the carriage return.

Compare the following 2 screenshots to see the difference this statement makes in the date format. The first image shows what happens when the Format_Dates_Carriage_Return macro is executed without having the statement under analysis. The formatted date, which corresponds to the match between Honduras and Ecuador, is June 20 of 2014.

Example of Excel date not fully formatted

The image below shows the result of including the Range.RowHeight property for purposes of doubling the row height. The formatted date corresponds to that of the match between Argentina and Iran (June 21 of 2014).

Excel date before text wrap with double row height

Notice that this format isn’t yet what we want. More precisely, the month and year that correspond to the formatted date are displayed on the same line. Element #5, which I explain below, fixes this.

If the height of the cells whose date format you’re modifying is enough to fit all of the elements/lines, you may not need to include this particular statement in your date-formatting macro. In other cases, you may need to change the factor by which you multiply the current row height. In other words, instead of using the number 2 at the end of the statement (as I do in the sample macro), you may need to use a different number.

The use of the Range.RowHeight property is optional and doesn’t affect the date format of the selected cells. You may choose to omit it from your macros, or work with a different property.

The reason why I use RowHeight in the sample Format_Dates_Carriage_Return is for illustration purposes only. In particular, it ensures that the cell that I format using this macro shows the complete date.

Let’s take a look at the fifth and last of the new elements introduced in the sample Format_Dates_Carriage_Return macro:

Element #5: Range.WrapText Property

The Range.WrapText Property allows you to determine whether Excel wraps the text within the relevant range object. In the sample Format_Dates_Carriage_Return macro, that relevant range object is the range of cells returned by the Application.Selection property.

Within the Format_Dates_Carriage_Return macro, the WrapText property is used for purposes of wrapping the text within its own cell. More precisely, the following statement sets the property to True for all the cells within the range returned by the Selection property:

.WrapText = True

The last image I show when explaining the Range.RowHeight property above displays both the month and the year on the same line. The following image allows you to compare the results obtained when I execute: (i) the macro version that doesn’t include the WrapText property (for the date of the match between Argentina and Iran) and (ii) the macro version that uses the WrapText property (for the match between Germany and Ghana):

Excel date formatted with carriage return using VBA

Conclusion

This Excel tutorial explains the Range.NumberFormat property in great detail and shows how you can use it for purposes of formatting dates using VBA.

As you’ve probably realized, successfully applying date formats using VBA generally boils down to knowing and understanding the following 2 topics:

  • Item #1: The Range.NumberFormat property.
  • Item #2: Date format codes.

In addition to reading about these 2 items, you’ve seen 25 different date formatting examples using VBA. Such a long list of examples may seem a little excessive, and there are several similarities between some of the date formats I applied.

However, these 25 examples are evidence of the flexibility you have when formatting dates using VBA. At the same time, they provide a base for you to create your own macros to apply different date formats.

This Excel VBA Date Format Tutorial is accompanied by an Excel workbook containing the data and some versions of the macros I explain above. You can get immediate free access to this example workbook by subscribing to the Power Spreadsheets Newsletter.

Books Referenced In This Excel Tutorial

  • Alexander, Michael (2015). Excel Macros for Dummies. Hoboken, NJ: John Wiley & Sons Inc.
  • Walkenbach, John (2013). Excel VBA Programming for Dummies. Hoboken, NJ: John Wiley & Sons Inc.

Понравилась статья? Поделить с друзьями:
  • Change font style in word
  • Change font size in word
  • Change files to excel
  • Change fields in word
  • Change english to british english in word