Миф excel в ячейке дата

Функции для работы с датой и временем в VBA Excel. Синтаксис, параметры, спецсимволы, примеры. Функции, возвращающие текущие дату и время по системному таймеру.

Функция Date

Date – это функция, которая возвращает значение текущей системной даты. Тип возвращаемого значения – Variant/Date.

Синтаксис

Пример

Sub PrimerDate()

    MsgBox «Сегодня: « & Date

End Sub

Функция DateAdd

DateAdd – это функция, которая возвращает результат прибавления к дате указанного интервала времени. Тип возвращаемого значения – Variant/Date.

Синтаксис

DateAdd(interval, number, date)

Параметры

Параметр Описание
interval Обязательный параметр. Строковое выражение из спецсимволов, представляющее интервал времени, который требуется добавить.
number Обязательный параметр. Числовое выражение, задающее количество интервалов, которые необходимо добавить. Может быть как положительным (возвращается будущая дата), так и отрицательным (возвращается предыдущая дата).
date Обязательный параметр. Значение типа Variant/Date или литерал, представляющий дату, к которой должен быть добавлен интервал.

Таблицу аргументов (значений) параметра interval смотрите в параграфе «Приложение 1».

Примечание к таблице аргументов: три символа – y, d, w – указывают функции DateAdd на один день, который необходимо прибавить к исходной дате number раз.

Пример

Sub PrimerDateAdd()

    MsgBox «31.01.2021 + 1 месяц = « & DateAdd(«m», 1, «31.01.2021») ‘Результат: 28.02.2021

    MsgBox «Сегодня + 3 года = « & DateAdd(«yyyy», 3, Date)

    MsgBox «Сегодня — 2 недели = « & DateAdd(«ww», 2, Date)

    MsgBox «10:22:14 + 10 минут = « & DateAdd(«n», 10, «10:22:14») ‘Результат: 10:32:14

End Sub

Функция DateDiff

DateDiff – это функция, которая возвращает количество указанных интервалов времени между двумя датами. Тип возвращаемого значения – Variant/Long.

Синтаксис

DateDiff(interval, date1, date2, [firstdayofweek], [firstweekofyear])

Параметры

Параметр Описание
interval Обязательный параметр. Строковое выражение из спецсимволов, представляющее интервал времени, количество которых (интервалов) требуется вычислить между двумя датами.
date1, date2 Обязательные параметры. Значения типа Variant/Date, представляющие две даты, между которыми вычисляется количество указанных интервалов.
firstdayofweek Необязательный параметр. Константа, задающая первый день недели. По умолчанию – воскресенье.
firstweekofyear Необязательный параметр. Константа, задающая первую неделю года. По умолчанию – неделя, в которую входит 1 января.

Таблицу аргументов (значений) параметра interval смотрите в параграфе «Приложение 1».

Примечание к таблице аргументов: в отличие от функции DateAdd, в функции DateDiff спецсимвол "w", как и "ww", обозначает неделю. Но расчет осуществляется по разному. Подробнее об этом на сайте разработчиков.

Параметры firstdayofweek и firstweekofyear определяют правила расчета количества недель между датами.

Таблицы констант из коллекций firstdayofweek и firstweekofyear смотрите в параграфах «Приложение 2» и «Приложение 3».

Пример

Sub PrimerDateDiff()

‘Даже если между датами соседних лет разница 1 день,

‘DateDiff с интервалом «y» покажет разницу — 1 год

    MsgBox DateDiff(«y», «31.12.2020», «01.01.2021») ‘Результат: 1 год

    MsgBox DateDiff(«d», «31.12.2020», «01.01.2021») ‘Результат: 1 день

    MsgBox DateDiff(«n», «31.12.2020», «01.01.2021») ‘Результат: 1440 минут

    MsgBox «Полных лет с начала века = « & DateDiff(«y», «2000», Year(Now) 1)

End Sub

Функция DatePart

DatePart – это функция, которая возвращает указанную часть заданной даты. Тип возвращаемого значения – Variant/Integer.

Есть предупреждение по использованию этой функции.

Синтаксис

DatePart(interval, date, [firstdayofweek], [firstweekofyear])

Параметры

Параметр Описание
interval Обязательный параметр. Строковое выражение из спецсимволов, представляющее часть даты, которую требуется извлечь.
date Обязательные параметры. Значение типа Variant/Date, представляющее дату, часть которой следует извлечь.
firstdayofweek Необязательный параметр. Константа, задающая первый день недели. По умолчанию – воскресенье.
firstweekofyear Необязательный параметр. Константа, задающая первую неделю года. По умолчанию – неделя, в которую входит 1 января.

Таблицу аргументов (значений) параметра interval смотрите в параграфе «Приложение 1». В третьей графе этой таблицы указаны интервалы значений, возвращаемых функцией DatePart.

Таблицы констант из коллекций firstdayofweek и firstweekofyear смотрите в параграфах «Приложение 2» и «Приложение 3».

Пример

Sub PrimerDatePart()

    MsgBox DatePart(«y», «31.12.2020») ‘Результат: 366

    MsgBox DatePart(«yyyy», CDate(43685)) ‘Результат: 2019

    MsgBox DatePart(«n», CDate(43685.45345)) ‘Результат: 52

    MsgBox «День недели по счету сегодня = « & DatePart(«w», Now, vbMonday)

End Sub

Функция DateSerial

DateSerial – это функция, которая возвращает значение даты для указанного года, месяца и дня. Тип возвращаемого значения – Variant/Date.

Синтаксис

DateSerial(year, month, day)

Параметры

Параметр Описание
year Обязательный параметр типа Integer. Числовое выражение, возвращающее значение от 100 до 9999 включительно.
month Обязательный параметр типа Integer. Числовое выражение, возвращающее любое значение (в пределах Integer), а не только от 1 до 12.*
day Обязательный параметр типа Integer. Числовое выражение, возвращающее любое значение (в пределах Integer), а не только от 1 до 31.*

* Функция DateSerial автоматически пересчитывает общее количество дней в полные месяцы и остаток, общее количество месяцев в полные годы и остаток (подробнее в примере).

Пример

Sub PrimerDateSerial()

    MsgBox DateSerial(2021, 2, 10) ‘Результат: 10.02.2020

    MsgBox DateSerial(2020, 1, 400) ‘Результат: 03.02.2021

End Sub

Разберем подробнее строку DateSerial(2020, 1, 400):

  • 400 дней = 366 дней + 31 день + 3 дня;
  • 366 дней = 1 год, так как по условию month:=1, значит февраль 2020 входит в расчет, а в нем – 29 дней;
  • 31 день = 1 месяц, так как сначала заполняется январь (по условию month:=1);
  • 3 дня – остаток.

В итоге получается:

DateSerial(2020+1, 1+1, 3) = DateSerial(2021, 2, 3)

Функция DateValue

DateValue – это функция, которая преобразует дату, указанную в виде строки, в значение типа Variant/Date (время игнорируется).

Синтаксис

Параметр date – строковое выражение, представляющее дату с 1 января 100 года по 31 декабря 9999 года.

Пример

Sub PrimerDateValue()

    MsgBox DateValue(«8 марта 2021») ‘Результат: 08.03.2021

    MsgBox DateValue(«17 мая 2021 0:59:15») ‘Результат: 17.05.2021

End Sub

Функция DateValue игнорирует время, указанное в преобразуемой строке, но если время указано в некорректном виде (например, «10:60:60»), будет сгенерирована ошибка.

Функция Day

Day – это функция, которая возвращает день месяца в виде числа от 1 до 31 включительно. Тип возвращаемого значения – Variant/Integer.

Синтаксис

Параметр date – любое числовое или строковое выражение, представляющее дату.

Пример

Sub PrimerDay()

    MsgBox Day(Now)

End Sub

Функция IsDate

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

Синтаксис

Параметр expression – это переменная, возвращающая дату или строковое выражение, распознаваемое как дата или время.

Значение, возвращаемое переменной expression, не должно выходить из диапазона допустимых дат: от 1 января 100 года до 31 декабря 9999 года (для Windows).

Пример

Sub PrimerIsDate()

    MsgBox IsDate(«18 апреля 2021») ‘Результат: True

    MsgBox IsDate(«31 февраля 2021») ‘Результат: False

    MsgBox IsDate(«4.10.20 11:12:54») ‘Результат: True

End Sub

Функция Hour

Hour – это функция, которая возвращает количество часов в виде числа от 0 до 23 включительно. Тип возвращаемого значения – Variant/Integer.

Синтаксис

Параметр time – любое числовое или строковое выражение, представляющее время.

Пример

Sub PrimerHour()

    MsgBox Hour(Now)

    MsgBox Hour(«22:36:54»)

End Sub

Функция Minute

Minute – это функция, которая возвращает количество минут в виде числа от 0 до 59 включительно. Тип возвращаемого значения – Variant/Integer.

Синтаксис

Параметр time – любое числовое или строковое выражение, представляющее время.

Пример

Sub PrimerMinute()

    MsgBox Minute(Now)

    MsgBox Minute(«22:36:54»)

End Sub

Функция Month

Month – это функция, которая возвращает день месяца в виде числа от 1 до 12 включительно. Тип возвращаемого значения – Variant/Integer.

Синтаксис

Параметр date – любое числовое или строковое выражение, представляющее дату.

Пример

Sub PrimerMonth()

    MsgBox Month(Now)

End Sub

Функция MonthName

MonthName – это функция, которая возвращает название месяца в виде строки.

Синтаксис

MonthName(month, [abbreviate])

Параметры

Параметр Описание
month Обязательный параметр. Числовое обозначение месяца от 1 до 12 включительно.
abbreviate Необязательный параметр. Логическое значение: True – возвращается сокращенное название месяца, False (по умолчанию) – название месяца не сокращается.

Пример

Sub PrimerMonthName()

    MsgBox MonthName(10) ‘Результат: Октябрь

    MsgBox MonthName(10, True) ‘Результат: окт

End Sub

Функция Now

Now – это функция, которая возвращает текущую системную дату и время. Тип возвращаемого значения – Variant/Date.

Синтаксис

Пример

Sub PrimerNow()

    MsgBox Now

    MsgBox Day(Now)

    MsgBox Hour(Now)

End Sub

Функция Second

Second – это функция, которая возвращает количество секунд в виде числа от 0 до 59 включительно. Тип возвращаемого значения – Variant/Integer.

Синтаксис

Параметр time – любое числовое или строковое выражение, представляющее время.

Пример

Sub PrimerSecond()

    MsgBox Second(Now)

    MsgBox Second(«22:30:14»)

End Sub

Функция Time

Time – это функция, которая возвращает значение текущего системного времени. Тип возвращаемого значения – Variant/Date.

Синтаксис

Пример

Sub PrimerTime()

    MsgBox «Текущее время: « & Time

End Sub

Функция TimeSerial

TimeSerial – это функция, которая возвращает значение времени для указанного часа, минуты и секунды. Тип возвращаемого значения – Variant/Date.

Синтаксис

TimeSerial(hour, minute, second)

Параметры

Параметр Описание
hour Обязательный параметр типа Integer. Числовое выражение, возвращающее значение от 0 до 23 включительно.
minute Обязательный параметр типа Integer. Числовое выражение, возвращающее любое значение (в пределах Integer), а не только от 0 до 59.*
second Обязательный параметр типа Integer. Числовое выражение, возвращающее любое значение (в пределах Integer), а не только от 0 до 59.*

* Функция TimeSerial автоматически пересчитывает общее количество секунд в полные минуты и остаток, общее количество минут в полные часы и остаток (подробнее в примере).

Пример

Sub PrimerTime()

    MsgBox TimeSerial(5, 16, 4) ‘Результат: 5:16:04

    MsgBox TimeSerial(5, 75, 158) ‘Результат: 6:17:38

End Sub

Разберем подробнее строку TimeSerial(5, 75, 158):

  • 158 секунд = 120 секунд (2 минуты) + 38 секунд;
  • 75 минут = 60 минут (1 час) + 15 минут.

В итоге получается:

TimeSerial(5+1, 15+2, 38) = TimeSerial(6, 17, 38)

Функция TimeValue

TimeValue – это функция, которая преобразует время, указанное в виде строки, в значение типа Variant/Date (дата игнорируется).

Синтаксис

Параметр time – строковое выражение, представляющее время с 0:00:00 по 23:59:59 включительно.

Пример

Sub PrimerTimeValue()

    MsgBox TimeValue(«6:45:37 PM») ‘Результат: 18:45:37

    MsgBox TimeValue(«17 мая 2021 3:59:15 AM») ‘Результат: 3:59:15

End Sub

Функция TimeValue игнорирует дату, указанную в преобразуемой строке, но если дата указана в некорректном виде (например, «30.02.2021»), будет сгенерирована ошибка.

Функция Weekday

Weekday – это функция, которая возвращает день недели в виде числа от 1 до 7 включительно. Тип возвращаемого значения – Variant/Integer.

Синтаксис

Weekday(date, [firstdayofweek])

Параметры

Параметр Описание
date Обязательный параметр. Любое выражение (числовое, строковое), отображающее дату.
firstdayofweek Константа, задающая первый день недели. По умолчанию – воскресенье.

Таблицу констант из коллекции firstdayofweek смотрите в параграфе «Приложение 2».

Пример

Sub PrimerWeekday()

    MsgBox Weekday(«23 апреля 2021», vbMonday) ‘Результат: 5

    MsgBox Weekday(202125, vbMonday) ‘Результат: 6

End Sub

Функция WeekdayName

WeekdayName – это функция, которая возвращает название дня недели в виде строки.

Синтаксис

WeekdayName(weekday, [abbreviate], [firstdayofweek])

Параметры

Параметр Описание
weekday Обязательный параметр. Числовое обозначение дня недели от 1 до 7 включительно.
abbreviate Необязательный параметр. Логическое значение: True – возвращается сокращенное название дня недели, False (по умолчанию) – название дня недели не сокращается.
firstdayofweek Константа, задающая первый день недели. По умолчанию – воскресенье.

Таблицу констант из коллекции firstdayofweek смотрите в параграфе «Приложение 2».

Пример

Sub PrimerWeekdayName()

    MsgBox WeekdayName(3, True, vbMonday) ‘Результат: Ср

    MsgBox WeekdayName(3, , vbMonday) ‘Результат: среда

    MsgBox WeekdayName(Weekday(Now, vbMonday), , vbMonday)

End Sub

Функция Year

Year – это функция, которая возвращает номер года в виде числа. Тип возвращаемого значения – Variant/Integer.

Синтаксис

Параметр date – любое числовое или строковое выражение, представляющее дату.

Пример

Sub PrimerYear()

    MsgBox Year(Now)

End Sub

Приложение 1

Таблица аргументов (значений) параметраinterval для функций DateAdd, DateDiff и DatePart:

Аргумент Описание Интервал значений
yyyy Год 100 – 9999
q Квартал 1 – 4
m Месяц 1 – 12
y День года 1 – 366
d День месяца 1 – 31
w День недели 1 – 7
ww Неделя 1 – 53
h Часы 0 – 23
n Минуты 0 – 59
s Секунды 0 – 59

В третьей графе этой таблицы указаны интервалы значений, возвращаемых функцией DatePart.

Приложение 2

Константы из коллекции firstdayofweek:

Константа Значение Описание
vbUseSystem 0 Используются системные настройки
vbSunday 1 Воскресенье (по умолчанию)
vbMonday 2 Понедельник
vbTuesday 3 Вторник
vbWednesday 4 Среда
vbThursday 5 Четверг
vbFriday 6 Пятница
vbSaturday 7 Суббота

Приложение 3

Константы из коллекции firstweekofyear:

Константа Значение Описание
vbUseSystem 0 Используются системные настройки.
vbFirstJan1 1 Неделя, в которую входит 1 января (по умолчанию).
vbFirstFourDays 2 Неделя, в которую входит не менее четырех дней нового года.
vbFirstFullWeek 3 Первая полная неделя года.

ГЛАВНАЯ

ТРЕНИНГИ

   Быстрый старт
   Расширенный Excel
   Мастер Формул
   Прогнозирование
   Визуализация
   Макросы на VBA

КНИГИ

   Готовые решения
   Мастер Формул
   Скульптор данных

ВИДЕОУРОКИ

ПРИЕМЫ

   Бизнес-анализ
   Выпадающие списки
   Даты и время
   Диаграммы
   Диапазоны
   Дубликаты
   Защита данных
   Интернет, email
   Книги, листы
   Макросы
   Сводные таблицы
   Текст
   Форматирование
   Функции
   Всякое
PLEX

   Коротко
   Подробно
   Версии
   Вопрос-Ответ
   Скачать
   Купить

ПРОЕКТЫ

ОНЛАЙН-КУРСЫ

ФОРУМ

   Excel
   Работа
   PLEX

© Николай Павлов, Planetaexcel, 2006-2022
info@planetaexcel.ru


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

Техническая поддержка сайта

ООО «Планета Эксел»

ИНН 7735603520


ОГРН 1147746834949
        ИП Павлов Николай Владимирович
        ИНН 633015842586
        ОГРНИП 310633031600071 

Когда я пытаюсь вывести дату в Excel в формате dd/mm/yyyy hh, у меня это получается, дата выглядит, как и предполагалось:

20/10/2016 17

20/10/2016 18

В случае выше я вывожу дату и время следующим образом:

nRowDate = 1
For nDay = 20 To 21
    For nHour = 0 To 23
                If (nDay < 10) Then
                    Str = "0" + CStr(nDay) + "/" + MonthNumber + "/" + Year + " "
                Else
                    Str = CStr(nDay) + "/" + MonthNumber + "/" + Year + " "
                End If
                
                If (nHour < 10) Then
                    Str = Str + "0" + CStr(nHour)
                Else
                    Str = Str + CStr(nHour)
                End If
                
                Date_Array(nRowDate) = Str
                nRowDate = nRowDate + 1
                Cells(nRowDate, 1).Value = Format(Str, "dd/mm/yyyy hh")
          
    Next nHour
Next nDay

Но вывести дату в формате dd/mm/yyyy hh:mm:ss у меня не получается, вывод выглядит следующим образом:

20.10.2016 00:00:00

20.10.2016 00:00:10

Вот код:

nRowDate = 1
For nDay = 20 To 21
    For nHour = 0 To 23
        For nMinutes = 0 To 60
            For nSec = 0 To 5
                If (nDay < 10) Then
                    Str = "0" + CStr(nDay) + "/" + MonthNumber + "/" + Year + " "
                Else
                    Str = CStr(nDay) + "/" + MonthNumber + "/" + Year + " "
                End If
                
                If (nHour < 10) Then
                    Str = Str + "0" + CStr(nHour)
                Else
                    Str = Str + CStr(nHour)
                End If
                
                If (nMinutes < 10) Then
                    Str = Str + ":0" + CStr(nMinutes)
                Else
                   Str = Str + ":" + CStr(nMinutes)
                End If
                
                If (nSec = 0) Then
                    Str = Str + ":00"
                Else
                    Str = Str + ":0" + CStr(nSec * 10)
                End If
            
                Date_Array(nRowDate) = Str
                nRowDate = nRowDate + 1
                Cells(nRowDate, 1).Value = Format(Str, "dd/mm/yyyy hh:mm:ss")
        
            Next nSec
        Next nMinutes
    Next nHour
Next nDay

Где я ошиблась?..

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.

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

Обращение к конкретной ячейке

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

Полный путь к ячейке A1 в Книге1 на Листе1 можно записать двумя вариантами:

  • С помощью Range
  • С помощью Cells

Пример 1: Обратиться к ячейке A3 находящейся в Книге1 на Листе1

Workbooks("Книга1.xls").Sheets("Лист1").Range("A3") ' Обратиться к ячейке A3
Workbooks("Книга1.xls").Sheets("Лист1").Cells(3, 1) ' Обратиться к ячейке в 3-й строке и 1-й колонке (A3)

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

Пример 2: Обратиться к ячейке A1 в текущей книге на активном листе

Range("A1")
Cells(1, 1)

Если всё же путь к книге или листу необходим, но не хочется его писать при каждом обращении к ячейкам, можно использовать конструкцию With End With. При этом, обращаясь к ячейкам, необходимо использовать в начале «.» (точку).

Пример 3: Обратиться к ячейке A1 и B1 в Книге1 на Листе2.

With Workbooks("Книга1").Sheets("Лист2")
  ' Вывести значение ячейки A1, которая находится на Листе2
  MsgBox .Range("A1")
  ' Вывести значение ячейки B1, которая находится на Листе2
  MsgBox .Range("B1")
End With

Так же, можно обратиться и к активной (выбранной в данный момент времени) ячейке.

Пример 4: Обратиться к активной ячейке на Листе3 текущей книги.

Application.ActiveCell ' полная запись
ActiveCell ' краткая запись

Чтение значения из ячейки

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

  • Value2 — базовое значение ячейки, т.е. как оно хранится в самом Excel-е. В связи с чем, например, дата будет прочтена как число от 1 до 2958466, а время будет прочитано как дробное число. Value2 — самый быстрый способ чтения значения, т.к. не происходит никаких преобразований.
  • Value — значение ячейки, приведенное к типу ячейки. Если ячейка хранит дату, будет приведено к типу Date. Если ячейка отформатирована как валюта, будет преобразована к типу Currency (в связи с чем, знаки с 5-го и далее будут усечены).
  • Text — визуальное отображение значения ячейки. Например, если ячейка, содержит дату в виде «число месяц прописью год», то Text (в отличие от Value и Value2) именно в таком виде и вернет значение. Использовать Text нужно осторожно, т.к., если, например, значение не входит в ячейку и отображается в виде «#####» то Text вернет вам не само значение, а эти самые «решетки».

По-умолчанию, если при обращении к ячейке не указывать способ чтения значения, то используется способ Value.

Пример 5: В ячейке A1 активного листа находится дата 01.03.2018. Для ячейки выбран формат «14 марта 2001 г.». Необходимо прочитать значение ячейки всеми перечисленными выше способами и отобразить в диалоговом окне.

MsgBox Cells(1, 1)        ' выведет 01.03.2018
MsgBox Cells(1, 1).Value  ' выведет 01.03.2018
MsgBox Cells(1, 1).Value2 ' выведет 43160
MsgBox Cells(1, 1).Text   ' выведет 01 марта 2018 г.

Dim d As Date
d = Cells(1, 1).Value2    ' числовое представление даты преобразуется в тип Date
MsgBox d                  ' выведет 01.03.2018

Пример 6: В ячейке С1 активного листа находится значение 123,456789. Для ячейки выбран формат «Денежный» с 3 десятичными знаками. Необходимо прочитать значение ячейки всеми перечисленными выше способами и отобразить в диалоговом окне.

MsgBox Range("C1")        ' выведет 123,4568
MsgBox Range("C1").Value  ' выведет 123,4568
MsgBox Range("C1").Value2 ' выведет 123,456789
MsgBox Range("C1").Text   ' выведет 123,457р.

Dim c As Currency
c = Range("C1").Value2    ' значение преобразуется в тип Currency
MsgBox c                  ' выведет 123,4568

Dim d As Double
d = Range("C1").Value2    ' значение преобразуется в тип Double
MsgBox d                  ' выведет 123,456789

При присвоении значения переменной или элементу массива, необходимо учитывать тип переменной. Например, если оператором Dim задан тип Integer, а в ячейке находится текст, при выполнении произойдет ошибка «Type mismatch». Как определить тип значения в ячейке, рассказано в следующей статье.

Пример 7: В ячейке B1 активного листа находится текст. Прочитать значение ячейки в переменную.

Dim s As String
Dim i As Integer
s = Range("B1").Value2 ' успех
i = Range("B1").Value2 ' ошибка

Таким образом, разница между Text, Value и Value2 в способе получения значения. Очевидно, что Value2 наиболее предпочтителен, но при преобразовании даты в текст (например, чтобы показать значение пользователю), нужно использовать функцию Format.

Запись значения в ячейку

Осуществить запись значения в ячейку можно 2 способами: с помощью Value и Value2. Использование Text для записи значения не возможно, т.к. это свойство только для чтения.

Пример 8: Записать в ячейку A1 активного листа значение 123,45

Range("A1") = 123.45
Range("A1").Value = 123.45
Range("A1").Value2 = 123.45

Все три строки запишут в A1 одно и то же значение.

Пример 9: Записать в ячейку A2 активного листа дату 1 марта 2018 года

Cells(2, 1) = #3/1/2018#
Cells(2, 1).Value = #3/1/2018#
Cells(2, 1).Value2 = #3/1/2018#

В данном примере тоже запишется одно и то же значение в ячейку A2 активного листа.

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

Like this post? Please share to your friends:
  • Миф excel буква столбца по номеру
  • Миф excel как очистить лист
  • Миф excel активный лист
  • Миф excel как добавить лист
  • Миф excel with описание