Vba 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 Первая полная неделя года.

Главная » Функции VBA »

28 Апрель 2011              326667 просмотров

  • Date() — возвращает текущую системную дату. Установить ее можно при помощи одноименного оператора, например, так:
  • Time() — возвращает текущее системное время
  • Now() — возвращает дату и время вместе.
  • DateAdd() — возможность добавить к дате указанное количество лет, кварталов, месяцев и так далее — вплоть до секунд. Интервалы(год, месяц и т.д.) указываются в текстовом формате. Список допустимых значений:
    «yyyy» Год
    «q» Квартал
    «m» Месяц
    «y» День года
    «d» День
    «w» День недели
    «ww» Неделя
    «h» Час
    «n» Минута
    «s» Секунда
    Сам синтаксис обращения незамысловат. Сначала указываем интервал, затем сколько единиц добавить и самый последний аргумент — к какой дате(включая время, кстати). Например, чтобы добавить 3 года к текущей дате-времени, надо записать функцию так:
    MsgBox DateAdd(«yyyy», 3, Now)
    Но что интереснее — можно не только добавлять, но и отнимать. Функция не изменится, мы просто должны записать кол-во добавляемых периодов со знаком минус. Отнимем три года от текущей даты-времени:
    MsgBox DateAdd(«yyyy», -3, Now)
  • DateDiff() — возможность получить разницу между датами (опять таки в единицах от лет до секунд).
        Dim lDaysCnt As Long
        lDaysCnt = DateDiff("d", "20.11.2012", Now)
        MsgBox "С 20.11.2012 прошло дней: " & lDaysCnt

    Первый аргумент определяет период времени, в котором необходимо вернуть разницу между датами. Допустимые значения:
    «yyyy» Год
    «q» Квартал
    «m» Месяц
    «y» День года
    «d» День
    «w» День недели
    «ww» Неделя
    «h» Час
    «n» Минута
    «s» Секунда
    Наиболее полезна DateDiff при вычислении полных лет. Например, чтобы вычислить сколько лет на текущий момент человеку, в зависимости от даты рождения, можно использовать функцию так:

    MsgBox DateDiff("yyyy", "20.12.1978", Now)

    Без этой функции вычислить кол-во полных лет гораздо сложнее.

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

    MsgBox "Номер недели года: " & DatePart("ww", Now)
  • DateSerial() — возможность создать значение даты, задавая месяц, год и день числовыми значениями:
  • MsgBox DateSerial(2012, 6, 7)
  • DateValue()— делает то же, что и DateSerial(). Отличия — в формате принимаемых значений. Эта функция в качестве аргумента принимает дату в текстовом формате и преобразует её в формат даты:
        MsgBox DateValue("07.06.12")

    Аналогичным образом (для времени) работают TimeSerial() и TimeValue()

  • Day(), Year(), Month(), Weekday(), Hour(), Minute(), Second() — специализированные заменители функции DatePart(), которые возвращают нужную часть даты/времени (которую именно — видно из названия).
  • MonthName() — возвращает имя месяца словами по его номеру. Возвращаемое значение зависит от региональных настроек. Если они русские, то вернется русское название месяца.
  • Timer() — возвращает количество секунд, прошедших с полуночи.

Статья помогла? Сделай твит, поделись ссылкой с друзьями!

In this Article

  • VBA Date Function
  • VBA Now Function
  • VBA Time Function
  • VBA DateAdd Function
  • VBA DateDiff Function
  • VBA DatePart Function
  • VBA DateSerial Function
  • VBA DateValue Function
  • VBA Day Function
  • VBA Hour Function
  • VBA Minute Function
  • VBA Second Function
  • VBA Month Function
  • VBA MonthName Function
  • VBA TimeSerial Function
  • VBA TimeValue Function
  • VBA Weekday Function
  • VBA WeekdayName Function
  • VBA Year Function
  • Comparing Dates in VBA

This tutorial will cover the different built-in VBA Date Functions.

VBA Date Function

You can use the Date Function to return the current date.

The syntax of the Date Function is Date(). It has no arguments.

The following code shows you how to use the Date Function:

Sub UsingTheDateFunction()

Dim theDate As Date
theDate = Date()

Debug.Print theDate

End Sub

The result shown in the Immediate Window is:

Using the Date Function in VBA

VBA Now Function

You can use the Now Function to return the current date and time.

The syntax of the Now Function is Now(). It has no arguments.

The following code shows you how to use the Now Function:

Sub UsingTheNowFunction()

Dim theDate As Date
theDate = Now()

Debug.Print theDate

End Sub

The result is:

Using the Now Function in VBA

VBA Time Function

You can use the Time Function to return the current time.

The syntax of the Time Function is Time(). It has no arguments.

The following code shows you how to use the Time Function:

Sub UsingTheTimeFunction()

Dim theTime As Date
theTime = Time()

Debug.Print theTime

End Sub

The result is:

Using the Time Function in VBA

VBA DateAdd Function

You can use the DateAdd Function to add a date/time interval to a date or time, and the function will return the resulting date/time.

The syntax of the DateAdd Function is:

DateAdd(Interval, Number, Date) where:

  • Interval – A string that specifies the type of interval to use. The interval can be one of the following values:

“d” – day
“ww” – week
“w” – weekday
“m” – month
“q” – quarter
“yyyy” – year
“y” – day of the year
“h” – hour
“n” – minute
“s” – second

  • Number – The number of intervals that you want to add to the original date/time.
  • Date – The original date/time.

Note: When using dates in your code you have to surround them with # or quotation marks.

The following code shows  how to use the DateAdd Function:

Sub UsingTheDateAddFunction()

Dim laterDate As Date

laterDate = DateAdd("m", 10, "11/12/2019")

Debug.Print laterDate

End Sub

The result is:

Using the DateAdd Function in VBA

VBA DateDiff Function

You can use the DateDiff Function in order to get the difference between two dates, based on a specified time interval.

The syntax of the DateDiff Function is:

DateDiff(Interval, Date1, Date2, [Firstdayofweek], [Firstweekofyear]) where:

  • Interval – A string that specifies the type of interval to use. The interval can be one of the following values:

“d” – day
“ww” – week
“w” – weekday
“m” – month
“q” – quarter
“yyyy” – year
“y” – day of the year
“h” – hour
“n” – minute
“s” – second

  • Date1 – A date value representing the earlier date.
  • Date2 – A date value representing the later date.
  • Firstdayofweek (Optional) – A constant that specifies the weekday that the function should use as the first day of the week. If blank Sunday is used as the first day of the week. Firstdayofweek can be one of the following values:

-vbSunday – uses Sunday as the first day of the week.
-vbMonday – uses Monday as the first day of the week.
-vbTuesday – uses Tuesday as the first day of the week.
-vbWednesday – uses Wednesday as the first day of the week.
-vbThursday – uses Thursday as the first day of the week.
-vbFriday – uses Friday as the first day of the week.
-vbSaturday – uses Saturday as the first day of the week.
-vbUseSystemDayOfTheWeek – uses the first day of the week that is specified by your system’s settings.

  • Firstweekofyear (Optional) – A constant that specifies the first week of the year. If blank then the Jan 1st week is used as the first week of the year. Firstweekofyear can be one of the following values:

-vbFirstJan1 – uses the week containing Jan 1st.
-vbFirstFourDays – uses the first week that contains at least four days in the new year.
-vbFirstFullWeek – uses the first full week of the year.
-vbSystem – uses the first week of the year as specified by your system settings.

The following code shows you how to use the DateDiff Function:

Sub UsingTheDateDiffFunction()
 
Dim theDifferenceBetweenTwoDates As Long
 
theDifferenceBetweenTwoDates = DateDiff("q", "11/11/2010", "10/12/2012")
 
Debug.Print theDifferenceBetweenTwoDates
 
End Sub

The result is:

Using The DateDiff Function in VBA

VBA DatePart Function

You can use the DatePart Function in order to return a part (day, week, quarter, month etc.) of a given date.

The syntax of the DatePart Function is:

DatePart(Interval, Date,[Firstdayofweek], [Firstweekofyear]) where:

  • Interval – A string that specifies the part of the date to return. The interval can be one of the following values:

“d” – day
“ww” – week
“w” – weekday
“m” – month
“q” – quarter
“yyyy” – year
“y” – day of the year
“h” – hour
“n” – minute
“s” – second

  • Date – The date that you want the function to return a part of.
  • Firstdayofweek (Optional) – A constant that specifies the weekday that the function should use as the first day of the week. If blank Sunday is used as the first day of the week. Firstdayofweek can be one of the following values:

-vbSunday – uses Sunday as the first day of the week.
-vbMonday – uses Monday as the first day of the week.
-vbTuesday – uses Tuesday as the first day of the week.
-vbWednesday – uses Wednesday as the first day of the week.
-vbThursday – uses Thursday as the first day of the week.
-vbFriday – uses Friday as the first day of the week.
-vbSaturday – uses Saturday as the first day of the week.
-vbUseSystemDayOfTheWeek – uses the first day of the week that is specified by your system’s settings.

  • Firstweekofyear (Optional) – A constant that specifies the first week of the year. If blank then the Jan 1st week is used as the first week of the year. Firstweekofyear can be one of the following values:

-vbFirstJan1 – uses the week containing Jan 1st.
-vbFirstFourDays – uses the first week that contains at least four days in the new year.
-vbFirstFullWeek – uses the first full week of the year.
-vbSystem – uses the first week of the year as specified by your system settings.

The following code shows you how to use the DatePart Function:

Sub UsingTheDatePartFunction()

Dim thePartOfTheDate As Integer

thePartOfTheDate = DatePart("yyyy", "12/12/2009")

Debug.Print thePartOfTheDate

End Sub

The result is:

Using the DatePart Function in VBA

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

VBA DateSerial Function

The VBA DateSerial Function takes an input year, month and day and returns a date.

The syntax of the DateSerial Function is:

DateSerial(Year,  Month, Day) where:

  • Year – An integer value between 100 and 9999 that represents the year.
  • Month – An integer value that represents the month.
  • Day – An integer value that represents the day.

The following code shows you how to use the DateSerial Function:

Sub UsingTheDateSerialFunction()

Dim theDate As Date

theDate = DateSerial(2010, 11, 10)

Debug.Print theDate

End Sub

The result is:

Using the Date Serial Function in VBA

VBA DateValue Function

The DateValue Function returns a Date when given a string representation of a date.

The syntax of the DateValue Function is:

DateValue(Date) where:

  • Date – A String representing the date.

The following code shows you how to use the DateValue Function:

Sub UsingTheDateValueFunction()

Dim theDate As Date

theDate = DateValue("October, 29, 2010")

Debug.Print theDate

End Sub

The result is:

Using the DateValue Function in VBA

VBA Day Function

You can use the Day Function to return the day of an input date.

The syntax of the Day Function is:

Day(Date_value) where:

  • Date_value – The date which you want to extract the day from.

The following code shows you how to use the Day Function:

Sub UsingTheDayFunction()

Dim theDay As Integer

theDay = Day("10/12/2010")

Debug.Print theDay

End Sub

The result is:

Using the Day Function in VBA

VBA Programming | Code Generator does work for you!

VBA Hour Function

You can use the Hour Function to return the hour of an input time.

The syntax of the Hour Function is:

Hour(Time) where:

  • Time – The time that you want to extract the hour from.

The following code shows you how to use the Hour Function:

Sub UsingTheHourFunction()
 
Dim theHour As Integer

theHour = Hour("2:14:17 AM")

Debug.Print theHour

End Sub

The result is:

Using the Hour Function in VBA

VBA Minute Function

You can use the Minute Function to return the minute value of an input time.

The syntax of the Minute Function is:

Minute(Time) where:

  • Time – The time that you want to extract the minute value from.

The following code shows you how to use the Minute Function:

Sub UsingTheMinuteFunction()
 
Dim theMinuteValue As Integer

theMinuteValue = Minute("2:14:17 AM")

Debug.Print theMinuteValue

End Sub

The result is:

Using The Minute Function in VBA

VBA Second Function

You can use the Second Function to return the second value of an input time.

The syntax of the Second Function is:

Second(Time) where:

  • Time – The time that you want to extract the second value from.

The following code shows you how to use the Second Function:

Sub UsingTheSecondFunction()
 
Dim theSecondValue As Integer

theSecondValue = Second("2:14:17 AM")

Debug.Print theSecondValue

End Sub

The result is:

Using the Second Function in VBA

VBA Month Function

You can use the Month Function to return the month of an input date.

The syntax of the Month Function is:

Month(Date_value) where:

  • Date_value – The date which you want to extract the month from.

The following code shows you how to use the Month Function:

Sub UsingTheMonthFunction()
 
Dim theMonth As Integer

theMonth = Month("11/18/2010")
Debug.Print theMonth

End Sub

The result is:

Using the Month Function in VBA

VBA MonthName Function

You can use the MonthName Function to return the name of a month from an input supplied month number.

The syntax of the MonthName Function is:

MonthName(Number_of_month, [Abbreviate]) where:

  • Number_of_month – An integer value between 1 and 12.
  • Abbreviate (Optional) – Specifies whether the month name should be abbreviated. If blank the default value of False is used.
Sub UsingTheMonthNameFunction()
 
Dim theMonthName As String

theMonthName = MonthName(12, True)
Debug.Print theMonthName

End Sub

The result is:

AutoMacro | Ultimate VBA Add-in | Click for Free Trial!

VBA TimeSerial Function

The TimeSerial Function takes an input hour, minute and second and returns a time.

The syntax of the TimeSerial Function is:

TimeSerial(Hour,  Minute, Second) where:

  • Hour – An integer value between 0 and 23 that represents the hour value.
  • Minute – An integer value between 0 and 59 that represents the minute value.
  • Second – An integer value between 0 and 59 that represents the second value.

The following code shows you how to use the TimeSerial Function:

Sub UsingTheTimeSerialFunction()

Dim theTime As Date
theTime = TimeSerial(1, 10, 15)

Debug.Print theTime

End Sub

The result is:

Using the TimeSerial Function in VBA

VBA TimeValue Function

The TimeValue Function returns a Time from a string representation of a date or time.

The syntax of the TimeValue Function is:

TimeValue(Time) where:

  • Time – A String representing the time.

The following code shows you how to use the TimeValue Function:

Sub UsingTheTimeValueFunction()

Dim theTime As Date
theTime = TimeValue("22:10:17")

Debug.Print theTime

End Sub

The result is:

The Time Value Function in VBA

VBA Weekday Function

You can use the Weekday Function to return an integer from 1 – 7 representing a day of the week from an input date.

The syntax of the Weekday Function is:

Weekday(Date, [Firstdayofweek]) where:

  • Date – The date that you want to extract the weekday value from.
  • Firstdayofweek (Optional) – A constant that specifies the weekday that the function should use as the first day of the week. If blank Sunday is used as the first day of the week. Firstdayofweek can be one of the following values:

-vbSunday – uses Sunday as the first day of the week.
-vbMonday – uses Monday as the first day of the week.
-vbTuesday – uses Tuesday as the first day of the week.
-vbWednesday – uses Wednesday as the first day of the week.
-vbThursday – uses Thursday as the first day of the week.
-vbFriday – uses Friday as the first day of the week.
-vbSaturday – uses Saturday as the first day of the week.
-vbUseSystemDayOfTheWeek – uses the first day of the week that is specified by your system’s settings.

The following code shows you how to use the Weekday Function:

Sub UsingTheWeekdayFunction()

Dim theWeekDay As Integer
theWeekDay = Weekday("11/20/2019")
Debug.Print theWeekDay

End Sub

The result is:

Using The WeekDay Function in VBA

VBA WeekdayName Function

You can use the WeekdayName Function to return the name of a weekday from an input supplied weekday number.

The syntax of the WeekdayName Function is:

WeekdayName(Weekday, [Abbreviate], [Firstdayoftheweek]) where:

  • Weekday – An integer value between 1 and 7.
  • Abbreviate (Optional) -Specifies whether the weekday name should be abbreviated. If blank the default value of False is used.
  • Firstdayofweek (Optional) – A constant that specifies the weekday that the function should use as the first day of the week. If blank Sunday is used as the first day of the week. Firstdayofweek can be one of the following values:

-vbSunday – uses Sunday as the first day of the week.
-vbMonday – uses Monday as the first day of the week.
-vbTuesday – uses Tuesday as the first day of the week.
-vbWednesday – uses Wednesday as the first day of the week.
-vbThursday – uses Thursday as the first day of the week.
-vbFriday – uses Friday as the first day of the week.
-vbSaturday – uses Saturday as the first day of the week.
-vbUseSystemDayOfTheWeek – uses the first day of the week that is specified by your system’s settings.

Sub UsingTheWeekdayNameFunction()
 
Dim theWeekdayName As String

theWeekdayName = WeekdayName(4)
Debug.Print theWeekdayName

End Sub

The result is:

Using the WeekdayName Function in VBA

AutoMacro | Ultimate VBA Add-in | Click for Free Trial!

VBA Year Function

You can use the Year Function to return the year of an input date.

The syntax of the Year Function is:

Year(Date_value) where:

  • Date_value – The date which you want to extract the year from.

The following code shows you how to use the Year Function:

Sub UsingTheYearFunction()

Dim theYear As Integer

theYear = Year("11/12/2010")
Debug.Print theYear

End Sub

The result is:

Using The Year Function in VBA

Comparing Dates in VBA

You can compare dates using the >, <, and = operators in VBA. The following code shows you how to compare two dates in VBA.

Sub ComparingDates()

Dim dateOne As Date
Dim dateTwo As Date

dateOne = "10/10/2010"
dateTwo = "11/11/2010"

If dateOne > dateTwo Then
Debug.Print "dateOne is the later date"

ElseIf dateOne = dateTwo Then
Debug.Print "The two dates are equal"

Else
Debug.Print "dateTwo is the later date"

End If
End Sub

Comparing Dates in VBA

Learn more about how to Format dates as strings by viewing this tutorial.

Excel VBA Date & Time Functions; Year, Month, Week & Day Functions

——————————————————

Contents:

VBA DateSerial Function

VBA DateValue Function

VBA TimeSerial Function

VBA TimeValue Function

VBA IsDate Function

VBA CDate Function

VBA DateAdd Function

VBA DateDiff Function

VBA DatePart Function

VBA Date Function

VBA Now Function

VBA MonthName Function

VBA Day Function

VBA Month Function

VBA Year Function

VBA Hour Function

VBA Minute Function

VBA Second Function

VBA WeekDay Function

VBA WeekdayName Function

Using Find Method to Search for a Date

—————————————————— 

Working with dates and times in Excel VBA can be tricky. There are a number of ways to represent dates in Excel. It is important to ensure that the Date will actually remain the date value which you actually mean to refer or use in your code. Date format is dependent on the regional and date-specific settings of your system / computer, and lack of understanding in using date functions can result in varying formats or incorrect interpretations. Excel VBA Date Functions are used in your code to work with and manipulate dates & times; to validate date values; convert serial numbers or strings to date formats; extract date parts like day, week, month & year; add and subtract date and time intervals; use the current date, the current time, or the day of the week; and so on.

We have explained in detail various aspects of using Dates & Times in Excel VBA, and also the Format Function to use Predefined Named Formats & to create User-Defined Formats, in our separate section of «Excel VBA Dates & Time, Format Function, User Defined Date, Number & String Formats». In this section we deal with some important Excel VBA Date Functions.

VBA DateSerial Function

The VBA DateSerial Function returns (Date value) a date for a specified year, month and day. Syntax: DateSerial(year, month, day). All 3 arguments are necessary to specify. Year argument is an Integer, can be a number within the range 100 and 9999, or can be a numeric expression. Month argument is an Integer, can be a number within a valid range of 1 and 12, or can be a numeric expression. Day argument is an Integer, can be a number within a valid range of 1 and 31, or can be a numeric expression. A numeric expression can also be used to specify relative dates for each argument, say, to represent a number of years or months or days before or after a specific date.

When values supplied for an argument exceeds its acceptable range, the increment will be to the next applicable unit, for example, supplying 14 as the value for the month argument will increment to the second month (February) of the next year. The Function will return an error in the case of any argument value being outside the range -32,768 to 32,767 or in case the final date (after evaluating the 3 arguments) falls outside the valid date range.

The supplied values for the year, month & day arguments are assumed to be Gregorian or Hijri, as per the Calendar property setting if Gregorian or Hijri. The Function returns the date part in the time period units of the current Calendar, so that if the date part to be returned is the year, the year value is a Gregorian year where the current Calendar is Gregorian.

It is advisable to use a four-digit year to ensure returning the correct Date by using this Function. Earlier versions of Windows interpret two-digit years based on certain defaults: Specifying two-digit years for the year argument are read as per user-defined desktop settings in Windows 98 or Windows 2000 systems, wherein the default settings read values from 0 to 29 as the years 2000 to 2029 and values from 30 to 99 as the years 1930 to1999 and for all other years the four-digit year is used.

Sub DateSerialFunc_1()

Dim MyDate As Variant

MyDate = DateSerial(2012, 5, 8)

‘returns «5/8/2012»

MsgBox MyDate

‘returns «May 08, 2012»

MsgBox Format(MyDate, «mmmm dd, yyyy»)

‘specify relative dates for an argument, using a numeric expression

‘returns «5/17/2010» (2 years before and 9 days later than the specified date of «5/8/2012»)

MsgBox DateSerial(2012 — 2, 5, 8 + 9)

End Sub

Sub DateSerialFunc_2()

Dim MyDate As Variant

‘Date increments to the second month (February) of the next year

MyDate = DateSerial(2012, 14, 8)

‘returns «2/8/2013»

MsgBox MyDate

‘returns «February 08, 2013»

MsgBox Format(MyDate, «mmmm dd, yyyy»)

‘—————-

‘Date will increment to 5th of next month (May is a 31 day month: 35-31 = 4)

MyDate = DateSerial(2012, 5, 35)

‘returns «6/4/2013»

MsgBox MyDate

‘returns «June 04, 2013»

MsgBox Format(MyDate, «mmmm dd, yyyy»)

‘—————-

‘Date will increment to 5th of next month (June is a 30 day month: 35-30 = 5)

MyDate = DateSerial(2012, 6, 35)

‘returns «7/5/2013»

MsgBox MyDate

‘returns «July 05, 2013»

MsgBox Format(MyDate, «mmmm dd, yyyy»)

‘—————-

‘gives a run time error — value for any argument is outside the range -32,768 to 32,767:

MyDate = DateSerial(2012, 32768, 5)

‘—————-

‘gives a run time error — final date (per the 3 arguments) falls outside the valid date range:

MyDate = DateSerial(9999, 16, 5)

End Sub

VBA DateValue Function

Use the DateValue function to convert a string to a Date (Date value). Syntax: DateValue(date). The date argument can be a string expression representing a date, or any expression representing a date or time or both. The expression should represent a date within the range January 1, 100 to December 31, 9999.

Refer below example which illustrates in detail on using the DateValue Function.

Sub DateValueFunc()

‘VBA DateValue Function

Dim vDate As Variant

‘you can assign a date literal to a Variant or Date variable

vDate = #7/5/2012#

‘returns «7/5/2012»

MsgBox DateValue(vDate)

‘—————

‘DateValue Function returns only the Date part (and not Time part) of an expression

Dim MyDate As Date

‘returns «8/13/2013 11.06.25 AM»

MyDate = Format(Now, «mmmm dd, yyyy hh:mm:ss«)

MsgBox MyDate

‘returns «8/13/2013»

MyDate = Format(DateValue(Now), «mmmm dd, yyyy hh:mm:ss«)

MsgBox MyDate

‘returns «August 13, 2013 00:00:00»

MsgBox Format(DateValue(«08/13/2013 11.06.25 AM»), «mmmm dd, yyyy hh:mm:ss»)

‘—————

‘for a string that includes only numbers, and which is separated by valid date separators, your System’s Short Date format determines the sequence for month, day & year for the DateValue Function.

‘for a system Short Date format of «m/d/yyyy» — returns «4/11/2013» meaning «April 11, 2013»

MsgBox DateValue(«4/11/2013»)

‘returns «April 11, 2013»

MsgBox Format(DateValue(«4/11/2013»), «mmmm dd, yyyy»)

‘for a system Short Date format of «m/d/yyyy» — returns «11/4/2013» meaning «November 04, 2013»

MsgBox DateValue(«11/4/2013»)

‘returns «November 04, 2013»

MsgBox Format(DateValue(«11/4/2013»), «mmmm dd, yyyy»)

‘—————

‘Month names, in both long or abbreviated forms, are also recognized by the DateValue function.

‘returns «11/4/2013»

MsgBox DateValue(«Nov 4, 13»)

‘—————

‘if the year is omitted, the current year is considered as per the system date in your computer.

‘returns «4/25/2013», if the current year is 2013

MsgBox DateValue(«4/25»)

‘—————

‘DateValue Function returns an error for an invalid format

vDate = #4:01:26 PM#

‘returns 12:00:00 AM» (DateValue Function returns only the Date part, and not Time part)

MsgBox DateValue(vDate)

vDate = «36:01:26«

‘returns an error because of invalid time format

MsgBox DateValue(vDate)

End Sub

VBA TimeSerial Function

The VBA TimeSerial Function returns a Time (Date value) for a specified hour, minute & second. Syntax: TimeSerial(hour, minute, second). All 3 arguments are necessary to specify.The hour argument is an Integer, a number within a valid range of 0 and 23, and can be any numeric expression. The minute argument is an Integer, a number within a valid range of 0 and 59, and can be any numeric expression. The second argument is an Integer, a number within a valid range of 0 and 59, and can be a numeric expression. A numeric expression can also be used to specify relative times for each argument, say, to represent a number of hours or minutes or seconds before or after a specific time.

When values supplied for an argument exceeds its acceptable range, the increment will be to the next applicable unit, for example, supplying 70 as the value for the minute argument will increment to the ten minutes of the next hour. The Function will return an error in the case of any argument value being outside the range -32,768 to 32,767 or in case the final date (after evaluating the 3 arguments) falls outside the valid date range.

Refer below example which illustrates in detail on using the TimeSerial Function.

Sub TimeSerialFunc()

Dim vTime As Variant

‘—————-

vTime = TimeSerial(14, 5, 18)

‘returns «2:05:18 PM» — as per your system’s Long Time Format setting — «h:mm:ss AM/PM«

‘changing your system’s Long Time Format setting to 24-hr format of «h:mm:ss» will return the time as «14:05:18»

MsgBox vTime

‘user-defined Time format with VBA Format Function — returns «02:5:18 P»

MsgBox Format(vTime, «hh:n:ss A/P»)

‘—————-

‘value of 85 supplied for minutes argument exceeds its acceptable range of 0 to 59, hence 85 will be evaluated as 1 hr 25 minutes thus incrementing time to the next hour

vTime = TimeSerial(14, 85, 18)

‘returns «3:25:18 PM»

MsgBox vTime

‘—————-

‘using a numeric expression to specify relative times for each argument:

Dim vHr As Variant, vMin As Variant, vSec As Variant

‘returns «7:08:24 PM»

MsgBox TimeSerial(19, 8, 24)

vHr = 3

vMin = 21

vSec = 4

‘returns «4:29:20 PM»

MsgBox TimeSerial(19 — vHr, 8 + vMin, 24 — vSec)

‘—————-

‘gives a run time error — value for any argument is outside the range -32,768 to 32,767:

MsgBox TimeSerial(19, 32768, 5)

End Sub 

VBA TimeValue Function

Use the VBA TimeValue function to convert a string to a time (Date value). Syntax: TimeValue(time) . The time argument can be a string expression representing a time, or any expression representing a time. The expression should represent a time within the range 0:00:00 (12:00:00 A.M.) to 23:59:59 (11:59:59 P.M.), inclusive.

Refer below example which illustrates in detail on using the TimeValue Function.

Sub TimeValueFunc()
‘VBA TimeValue Function

Dim vTime As Variant

‘—————

‘you can assign a time literal to a Variant or Date variable

vTime = #5:06:25 PM#

‘returns «5:06:25 PM»

MsgBox TimeValue(vTime)

‘—————

‘time values using a 12-hour or 24-hour format can be entered

‘returns «5:06:25 AM»

MsgBox TimeValue(«05:06:25»)

‘returns «5:06:25 PM»

MsgBox TimeValue(«17:06:25»)

‘—————

‘TimeValue Function returns only the Time part (and not Date part) of an expression

Dim MyTime As Date

‘returns «8/13/2013 11.06.25 AM»

MyTime = Format(Now, «mmmm dd, yyyy hh:mm:ss«)

MsgBox MyTime

‘returns «11.06.25 AM»

MyTime = Format(TimeValue(Now), «mmmm dd, yyyy hh:mm:ss«)

MsgBox MyTime

‘—————

‘TimeValue Function returns an error for an invalid format

vTime = «36:01:26«

‘returns an error because of invalid time format

MsgBox TimeValue(vTime)

End Sub

Example: Extract Date Part and Time Format from a cell value — use DateValue & TimeValue Functions

Sub DateValueTimeValue()
‘Extract Date Part and Time Format from a cell value (cell A1 contains the value 41463.251).

Dim MyDateTime As Date, MyDate As Date, MyTime As Date

Dim strDate As String, strTime As String

‘——————-

‘OPTION 1:

‘It is necessary to convert the expression (cell value) to a String or Date to use the DateValue / TimeValue functions.

‘cell A1 contains the value 41463.251 — Format function converts to a string value.

strDate = Format(Range(«A1»), «mm/dd/yyyy«)

strTime = Format(Range(«A1»), «hh:mm:ss AMPM«)

‘convert string to a Date by using DateValue & TimeValue functions which extract Date & Time parts

MyDate = DateValue(strDate)

MyTime = TimeValue(strTime)

‘returns «7/8/2013»

MsgBox MyDate

‘returns «6:01:26 AM»

MsgBox MyTime

MyDateTime = MyDate + MyTime

‘returns «7/8/2013 6:01:26 AM»

MsgBox MyDateTime

‘——————-

‘OPTION 2:

‘cell A1 contains the value 41463.251

‘returns «7/8/2013 6:01:26 AM», in date format

MyDateTime = Range(«A1«).Value

MsgBox MyDateTime

‘returns «7/8/2013»

MyDate = DateValue(MyDateTime)

MsgBox MyDate

‘returns «6:01:26 AM»

MyTime = TimeValue(MyDateTime)

MsgBox MyTime

‘——————-

‘OPTION 3:

‘cell A1 contains the value 41463.251

‘returns «7/8/2013 6:01:26 AM», in date format

MyDateTime = Range(«A1«).Value

MsgBox MyDateTime

‘returns «7/8/2013»

MyDate = MyDateTime — TimeValue(MyDateTime)

MsgBox MyDate

‘returns «6:01:26 AM»

MyTime = MyDateTime — DateValue(MyDateTime)

MsgBox MyTime

End Sub

VBA IsDate Function

The VBA IsDate Function is used to check if an expression is a Date or the expression can be converted to a valid Date or Time — the function returns True in this case, else False is returned. Syntax: IsDate(expression). Valid date can range from January 1, 100 to December 31, 9999 in Microsoft Windows operating system (will vary for different systems).

Sub IsDateFunc()

Dim var As Variant

var = «12/18/2011«

‘returns True (valid date)

MsgBox IsDate(var)

var = «18/12/2011«

‘returns True (valid date)

MsgBox IsDate(var)

var = «18/15/2011«

‘returns False (invalid date)

MsgBox IsDate(var)

var = «24 Jan, 2001«

‘returns True (valid date)

MsgBox IsDate(var)

var = «June 31, 2001«

‘returns False (invalid date)

MsgBox IsDate(var)

var = «18.12.11«

‘returns True (valid Time)

MsgBox IsDate(var)

var = «18.12.2011«

‘returns False (invalid Time)

MsgBox IsDate(var)

var = 21345

‘returns False (invalid Date/Time)

MsgBox IsDate(var)

End Sub

VBA CDate Function

Use the VBA CDate function to convert a value to a date (Date value). Syntax: CDate(expression). Refer below examples which explain the CDate Function in detail.

Sub CDateFunc_1()

‘CDate sets date format based on your system’s locale setting

‘returns «3/12/2013»

MsgBox CDate(41345)

‘returns «6:01:26 AM»

MsgBox CDate(0.251)

End Su

Sub CDateFunc_2()

Dim strDate As String, strTime As String

Dim vDate As Variant, vTime As Variant

strDate = «September 24, 1984«

strTime = «17:42:36«

‘set vDate to a Date value.

vDate = CDate(strDate)

‘returns «September 24, 1984»

MsgBox strDate

‘returns «9/24/1984» (CDate sets date format based on your system’s locale setting)

MsgBox vDate

‘set vTime to Date value.

vTime = CDate(strTime)

‘returns «17:42:36»

MsgBox strTime

‘returns «5:42:36 PM»

MsgBox vTime

End Sub

Sub InputBoxDateFormat()

‘date format with InputBox

Dim strDate As String

strDate = InputBox(«Enter date«)

‘Use the IsDate function to determine if a value can be converted to a date and time.

If IsDate(strDate) Then

‘CDate function converts a value to a date. CDate recognizes date formats based on your system’s locale setting. Ensure that you provide the day, month, and year in the correct sequence or order per your locale setting, or the date might not be correctly interpreted. A long date format containing a string value specifying a weekday like ‘Tuesday’ will not be recognized.

strDate = Format(CDate(strDate), «dd/mm/yyyy«)

‘displays date in the format of day-month-year

MsgBox strDate

Else

MsgBox «Invalid date»

End If

End Sub

VBA DateAdd Function

Use the VBA DateAdd Function to add or subtract a specified time interval to a Date — it returns (Date value) a future or past Date after adding or subtracting the specified time interval. Syntax: DateAdd(interval, number, date). All 3 arguments are necessary to specify. Interval argument is a String value, specifying the time interval you wish to add or subtract. Number argument is a numeric specifying the number of time intervals — use a positive number for future dates and a negative to get past dates. Date argument specifies the Date (Variant) to which you want to add or subtract the time interval.

Settings for the interval argument: yyyy — Year; q — Quarter; m — Month; y — Day of Year; d — Day; w — Weekday; ww — Week; h — Hour; n — Minute; s — Second.

Note that the Date returned by the function is as per your system-defined date format, and not by the format used in date argument.

Sub DateAddFunc()

Dim vDate As Variant

Dim strInterval As String

‘——————————

‘use y — Day of Year, d — Day or w — Weekday to add days to a date.

vDate = #8/11/2013#

strInterval = «y«

‘returns «8/16/2013»

MsgBox DateAdd(strInterval, 5, vDate)

strInterval = «d«

‘returns «8/16/2013»

MsgBox DateAdd(strInterval, 5, vDate)

strInterval = «w«

‘returns «8/16/2013»

MsgBox DateAdd(strInterval, 5, vDate)

‘——————————

vDate = #1/25/2004#

‘returns «2/25/2004»

MsgBox DateAdd(«m», 1, vDate)

vDate = #1/31/2004#

‘returns «2/29/2004» (2004 is a leap year)

MsgBox DateAdd(«m», 1, vDate)

vDate = #1/31/2004#

‘returns «2/28/2004»

MsgBox DateAdd(«ww», 4, vDate)

vDate = #1/25/2004#

‘returns «7/25/2004» — rounds off the number argument to the nearest whole number, if not a Long value.

MsgBox DateAdd(«q», 2.2, vDate)

vDate = #1/25/2004#

‘returns «7/25/2004» — rounds off the number argument to the nearest whole number, if not a Long value.

MsgBox DateAdd(«q», 2.2, vDate)

‘Note that the Date returned by the function is as per your system-defined date format, and not by the format used in date argument.

‘returns «7/27/1994».

MsgBox DateAdd(«yyyy», -2, «July 27, 1996»)

‘returns «2:23:12 PM».

MsgBox DateAdd(«n», -5, «14:28:12»)

‘returns «1:23:12 PM».

MsgBox DateAdd(«n», -65, «14:28:12»)

‘the Function will return an error, if the calculated date is not within the valid date range.

‘returns an error because the year precedes 100:

MsgBox DateAdd(«yyyy», -1900, «No 27, 1996»)

End Sub

VBA DateDiff Function

Use the VBA DateDiff Function to return the number (Long) of time intervals between two dates. Syntax:  DateDiff(interval, date1, date2, firstdayofweek, firstweekofyear). The arguments of interval, date1 & date2 are necessary to specify, while it is optional to specify firstdayofweek & firstweekofyear arguments. The interval argument is a String value, specifying the time interval which is used to calculate the date1 & date2 difference. Date1 & date2 are the two dates whose difference is being calculated. The firstdayofweek argument is a constant, specifying the first day of the week — Default is Sunday. The firstweekofyear argument is a constant, specifying the first week of the year — Default is the week containing January 1.

Settings for the interval argument: yyyy — Year; q — Quarter; m — Month; y — Day of Year; d — Day; w — Weekday; ww — Week; h — Hour; n — Minute; s — Second.

Constants to be used for the argument firstdayofweek: vbUseSystem (value 0) — use NLS API setting; vbSunday (this is the default) (value 1) — Sunday; vbMonday (value 2) — Monday; vbTuesday (value 3) — Tuesday; vbWednesday (value 4) — Wednesday; vbThursday (value 5) — Thursday; vbFriday (value 6) — Friday; vbSaturday ( value 7) — Saturday.

Constants to be used for the argument firstweekofyear: vbUseSystem (value 0) — use NLS API setting; vbFirstJan1 (this is the default) (value 1) — start with week in which January 1 occurs; vbFirstFourDays (value 2) — start with the first week which has at least four days in the year; vbFirstFullWeek (value 3) — start with the first full week of the year which has all 7 days.

Where date1 is later than date2, a negative value is returned by the DateDiff function.

Refer below examples which explain the DateDiff Function in detail.

Sub DateDiffFunc_1()

‘CALCULATE NO. OF DAYS BETWEEN TWO DATES

Dim vDate1 As Variant, vDate2 As Variant

Dim strInterval As String

‘use y — Day of Year or d — Day, to calculate no. of days between two dates.

vDate1 = #2/25/2004#

vDate2 = #3/5/2004#

strInterval = «y«

‘calculate number of days between two dates: returns 9 (2004 is leap year)

MsgBox DateDiff(strInterval, vDate1, vDate2)

strInterval = «d«

‘calculate number of days between two dates: returns -9 (2004 is leap year)

‘Where first date is later than second date, a negative value is returned by the DateDiff function.

MsgBox DateDiff(strInterval, vDate2, vDate1)

End Sub

Sub DateDiffFunc_2()

‘CALCULATE NO. OF WEEKS BETWEEN TWO DATES

Dim vDate1 As Variant, vDate2 As Variant

Dim strInterval As String

‘vDate1 is a Tuesday

vDate1 = #3/5/2013#

‘vDate2 is a Sunday

vDate2 = #3/17/2013#

‘returns Tuesday

MsgBox Format(vDate1, «dddd»)

‘returns Sunday

MsgBox Format(vDate2, «dddd»)

strInterval = «w«

‘calculate number of weeks between two dates — returns 1

‘vDate1 is a Tuesday, and when using interval of «w» (Weekday) DateDiff will count number of Tuesdays till vDate2

MsgBox DateDiff(strInterval, vDate1, vDate2)

strInterval = «ww«

‘calculate number of weeks between two dates — returns 2

‘when using interval of «ww» (Week) DateDiff counts number of calendar weeks (ie. the number of Sundays) from vDate1 till vDate2

MsgBox DateDiff(strInterval, vDate1, vDate2)

strInterval = «ww«

‘calculate number of weeks between two dates — returns 1

‘when using interval of «ww» (Week) DateDiff counts number of calendar weeks (ie. the number of Sundays) from vDate1 till vDate2

‘the firstdayofweek argument can affect the calculation when using interval of «ww» ((Week)- the Sunday falling on March 10, 2013 will not be counted below.

MsgBox DateDiff(strInterval, vDate1, vDate2, vbMonday)

‘vDate1 is a Sunday

vDate1 = #3/10/2013#

‘vDate2 is a Sunday

vDate2 = #3/17/2013#

strInterval = «ww«

‘calculate number of weeks between two dates (both vDate1 & vDate2 are Sundays) — returns 1

‘using interval of «ww» (Week), DateDiff counts number of Sundays from vDate1 till vDate2 — it counts vDate2 if it falls on a Sunday but not vDate1 even if it falls on a Sunday.

MsgBox DateDiff(strInterval, vDate1, vDate2)

End Sub

Sub DateDiffFunc_3()

‘CALCULATE NO. OF MONTHS ELAPSED FROM A SPECIFIC DATE TILL TODAY

Dim vDate1 As Variant, vDate2 As Variant

Dim strInterval As String

vDate1 = #8/25/2012#

‘current date

vDate2 = Now

MsgBox «Months elapsed from » & Format(vDate1, «mmmm d, yyyy») & » till today are: » & DateDiff(«m», vDate1, vDate2)

End Sub

Sub DateDiffFunc_4()

‘CALCULATE NO. OF QUARTERS / YEARS BETWEEN TWO DATES

Dim vDate1 As Variant, vDate2 As Variant

Dim strInterval As String

vDate1 = #12/31/2012#

vDate2 = #1/1/2013#

strInterval = «q«

‘calculate number of quarters between two dates: returns 1, even though the difference between dates is of 1 day

MsgBox DateDiff(strInterval, vDate1, vDate2)

strInterval = «yyyy«

‘calculate number of years between two dates: returns 1, even though the difference between dates is of 1 day

MsgBox DateDiff(strInterval, vDate1, vDate2)

End Sub

Sub DateDiffFunc_5()

‘If both dates are entered as ‘date literal’, the year specified therein is used for calculation in the DateDiff function. But if the dates are enclosed in double quotation marks («) & the year is omitted, the dates are evaluated by inserting the current year in your code.

Dim vDate1 As Variant, vDate2 As Variant

Dim strInterval As String

vDate1 = #2/25/2004#

vDate2 = #3/5/2004#

strInterval = «d«

‘calculate number of days between two dates — returns 9 (2004 is leap year)

MsgBox DateDiff(strInterval, vDate1, vDate2)

‘dates are enclosed in double quotation marks («) & the year is omitted

vDate1 = «2/25«

vDate2 = «3/5«

strInterval = «d«

‘calculate number of days between two dates — returns 8 (dates are evaluated by inserting the current year, which is not a leap year)

MsgBox DateDiff(strInterval, vDate1, vDate2)

End Sub

VBA DatePart Function

Use the VBA DatePart Function to return (Integer) a specified part of a date. Syntax: DatePart(interval, date, firstdayofweek, firstweekofyear). The arguments of interval & date are necessary to specify, while it is optional to specify firstdayofweek & firstweekofyear arguments. The interval argument is a String value — it is the time interval you want to return from the date being evaluated. The date argument is the Date value which is evaluated and whose time interval is to be returned. The firstdayofweek argument is a constant, specifying the first day of the week — Default is Sunday. The firstweekofyear argument is a constant, specifying the first week of the year — Default is the week containing January 1.

Settings / Constants for the interval, firstdayofweek &  firstweekofyear arguments are the same as in the VBA DateDiff Function explained above.

Refer below example which explains the DatePart Function in detail.

Sub DatePartFunc()

‘VBA DatePart Function

Dim vDate As Variant

Dim strInterval As String

vDate = #2/25/2004#

strInterval = «y«

‘returns 56 — the Day of year

MsgBox DatePart(strInterval, vDate)

strInterval = «d«

‘returns 25 — the Day part of the date

MsgBox DatePart(strInterval, vDate)

‘returns 28 — the minute part of the Time

MsgBox DatePart(«n», «14:28:12»)

‘returns 14 — the hour part of the Time

MsgBox DatePart(«h», «2:28:12 PM»)

‘returns 3 — the Weekday in date (#3/5/2013# is Tuesday), Sunday being the first day of week

MsgBox DatePart(«w», #3/5/2013#)

‘the firstdayofweek argument can affect the calculation when using interval of «w» ((Weekday)

‘returns 2 — the Weekday in date (#3/5/2013# is Tuesday), Monday being the first day of week

MsgBox DatePart(«w», #3/5/2013#, vbMonday)

‘returns the Week in date, considering Sunday to be the first day of week

‘returns 2 — second week starts from «1/6/2013» which is a Sunday

MsgBox DatePart(«ww», #1/7/2013#)

‘the firstdayofweek argument can affect the calculation when using interval of «ww» ((Week)

‘returns the Week in date, considering Tuesday to be the first day of week

‘returns 1 — second week starts from «1/8/2013» which is a Tuesday

MsgBox DatePart(«ww», #1/7/2013#, vbTuesday)

‘If both dates are entered as ‘date literal’, the year specified therein is used for calculation in the DateDiff function. But if the dates are enclosed in double quotation marks («) & the year is omitted, the dates are evaluated by inserting

the current year in your code.

‘returns 61 — day of year is evaluated for the year 2004 which is leap year

MsgBox DatePart(«y», #3/1/2004#)

‘returns 60 — day of year is evaluated by inserting the current year, which is not a leap year

MsgBox DatePart(«y», «3/1»)

End Sub

VBA Date Function

The VBA Date function returns (Date value) the current system date. VBA Code: MsgBox Date — returns the current system date (ex. «8/11/2013»)

VBA Now Function

The VBA Now function returns (Date value) the current system date and time. VBA Code: MsgBox Now — returns the current system date & ime (ex. «8/11/2013 2:26:32 PM»)

VBA MonthName Function

Use the VBA MonthName Function to return (String) the month name from a given number. Syntax: MonthName(month, abbreviate). The month argument is necessary to specify, and it is a numeric representing a month, ex. January is 1, February is 2, and so on. The abbreviate argument is optional, it is a Boolean value wherein False (default) indicating that the month name should not be abbreviated. VBA Code: MsgBox MonthName(8, True) — returns «Aug».

VBA Day Function

Use the VBA Day Function to return (Integer) the day of the month from a given date — it returns a whole number between 1 and 31. Syntax: Day(date). The date argument can be a Variant, or a numeric or string expression, representing a valid date. VBA Code: MsgBox Day(«August 24, 2012») — returns «24».

VBA Month Function

Use the VBA Month Function to return (Integer) the month of the year from a given date — it returns a whole number between 1 and 12. Syntax: Month(date). The date argument can be a Variant, or a numeric or string expression, representing a valid date. VBA Code: MsgBox Month(«August 24, 2012») — returns «8».

VBA Year Function

Use the VBA Year Function to return (Integer) the year from a given date — it returns a whole number. Syntax: Year(date). The date argument can be a Variant, or a numeric or string expression, representing a valid date. VBA Code: MsgBox Year(«August 24, 2012») — returns «2012».

VBA Hour Function

Use the VBA Hour Function to return (Integer) the hour from a given time — it returns a whole number between 0 and 23. Syntax: Hour(time). The time argument can be a Variant, or a numeric or string expression, representing a valid time. VBA Code: MsgBox Hour(«2:04:36 PM») — returns «14».

VBA Minute Function

Use the VBA Minute Function to return (Integer) the minute of the hour from a given time — it returns a whole number between 0 and 59. Syntax: Minute(time). The time argument can be a Variant, or a numeric or string expression, representing a valid time. VBA Code: MsgBox Minute(«2:04:36 PM») — returns «4».

VBA Second Function

Use the VBA Second Function to return (Integer) the second of the minute from a given time — it returns a whole number between 0 and 59. Syntax: Second(time). The time argument can be a Variant, or a numeric or string expression, representing a valid time. VBA Code: MsgBox Second(«2:04:36 PM») — returns «36».

VBA WeekDay Function

Use the VBA Weekday Function to return (Integer) the day of the week from a given date — it returns a whole number. Syntax: Weekday(date, firstdayofweek). The date argument is necessary to specify, and it can be a Variant, or a numeric or string expression, representing a valid date. The firstdayofweek argument (optional) is a constant, specifying the first day of the week — Default is Sunday.

Constants to be used for the argument firstdayofweek: vbUseSystem (value 0) — use NLS API setting; vbSunday (this is the default) (value 1) — Sunday; vbMonday (value 2) — Monday; vbTuesday (value 3) — Tuesday; vbWednesday (value 4) — Wednesday; vbThursday (value 5) — Thursday; vbFriday (value 6) — Friday; vbSaturday (value 7) — Saturday.

Values returned by the VBA Weekday Function (Constant — value — Day): vbSunday — 1 — Sunday; vbMonday — 2 — Monday; vbTuesday — 3 — Tuesday; vbWednesday — 4 — Wednesday; vbThursday — 5 — Thursday; vbFriday — 6 — Friday; vbSaturday — 7 — Saturday.

VBA Code: MsgBox Weekday(#8/24/2012#) — returns «6» (representing a Friday)

VBA Code: MsgBox Weekday(#8/24/2012#, vbMonday) — returns «5» (representing a Friday — first day of week is set as Monday instead of Sunday)

VBA WeekdayName Function

Use the VBA WeekdayName Function to return the name of the weekday — it returns a String. Syntax: WeekdayName(weekday, abbreviate, firstdayofweek). The weekday argument is necessary to specify — it is a numeric value representing the day of the week, depending on the firstdayofweek setting. The abbreviate argument (optional) is a Boolean value wherein False (default) indicates that the weekday name should not be abbreviated. The firstdayofweek argument (optional) is a numeric value, specifying the first day of the week — Default is Sunday.

Values for the argument firstdayofweek: vbUseSystem (value 0) — use NLS API setting; vbSunday (this is the default) (value 1) — Sunday; vbMonday (value 2) — Monday; vbTuesday (value 3) — Tuesday; vbWednesday (value 4) — Wednesday; vbThursday (value 5) — Thursday; vbFriday (value 6) — Friday; vbSaturday (value 7) — Saturday.

VBA Code: MsgBox WeekdayName(6) — returns «Friday»

VBA Code: MsgBox WeekdayName(6, True) — returns «Fri»

VBA Code: MsgBox WeekdayName(6, False, vbMonday) — returns «Saturday», first day of week is set as Monday instead of Sunday

Using Find Method to Search for a Date

Using a Valid Excel Date and Format: Using the Find Method to Find or Search a Date can be tricky. The date format should correspond to the default date format as set in your desktop/Windows which, unless specifically changed, should be in its standard format of «Short Date» or «Long Date’, viz. «1/22/2010» or «January 22, 2010». It does not matter in which date format it is displayed in the worksheet, only it should be a valid Excel date equating to a valid serial number.

Example — Search for a date within a range — refer Image 1.

Sub FindMethod_SearchDate()
‘Search for a date within a range — refer Image 1.
‘user enters the date he wants to find in Range («D2») — he enters the serial number 41200 in this cell;

‘user wants to find the date in search Range («A1:A100») — the range «$A$5» is returned in this example because the serial number 41200 corresponds to the date 18-Oct-12 which is entered in cell A5.

Dim rngFound As Range, rngSearch As Range, rngLast As Range

Dim strDate As String

‘search range to find the date:

Set rngSearch = ActiveSheet.Range(«A1:A100«)

Set rngLast = rngSearch.Cells(rngSearch.Cells.Count)

‘user enters the date he wants to find in Range: ActiveSheet.Range(«D2»).

‘Format(«7/18/10», «Short Date») returns «7/18/2010»; Format(«7/18/10», «Long Date») returns «Sunday, July 18, 2010».

‘Format Function in vba: Display a date according to your system’s short date format using «Short Date»; and using «Long Date» displays a date according to your system’s long date format.

strDate = Format(ActiveSheet.Range(«D2«), «Short Date»)

‘The IsDate function returns True if the expression is a valid date, else it returns False.

If IsDate(strDate) = False Then

MsgBox «Incorrect Date Format»

Exit Sub

End If

‘CDate converts a number or text string to a Date data type. CDate(40200) returns «1/22/2010»; CDate(«October 15, 2009») returns «10/15/2009»; CDate(«2:25:15 PM») returns «2:25:15 PM»; CDate(«hello») returns an error.

Set rngFound = rngSearch.Find(What:=CDate(strDate), After:=rngLast, LookIn:=xlFormulas, LookAt:=xlWhole, SearchOrder:=xlByRows, SearchDirection:=xlNext, MatchCase:=False, SearchFormat:=False)

   
If Not rngFound Is Nothing Then

‘return range address ($A$5 — in this example) if date is found:

MsgBox rngFound.Address

Else

‘if date is not found in search range:

MsgBox «Date Not Found»

End If

End Sub

Содержание

  1. Функции VBA для работы с датой/временем
  2. Функции даты-времени в VBA. Работа с датой и временем
  3. Синтаксис
  4. пример
  5. CDate
  6. Синтаксис
  7. пример
  8. DateAdd
  9. Синтаксис
  10. Параметр/Описание
  11. пример
  12. DateDiff
  13. Синтаксис
  14. Параметр/Описание
  15. пример
  16. DatePart
  17. Синтаксис
  18. Параметр/Описание
  19. пример
  20. DateSerial
  21. Синтаксис
  22. Параметр/Описание
  23. пример
  24. FormatDateTime
  25. Синтаксис
  26. Параметр/Описание
  27. пример
  28. IsDate
  29. Синтаксис
  30. пример
  31. Синтаксис
  32. пример
  33. Month
  34. Синтаксис
  35. пример
  36. Синтаксис
  37. пример
  38. MonthName
  39. Синтаксис
  40. Параметр Описание
  41. пример
  42. WeekDay
  43. Синтаксис
  44. Параметр/Описание
  45. WeekDayName
  46. пример
  47. Синтаксис
  48. пример
  49. Синтаксис
  50. пример
  51. Minute
  52. Синтаксис
  53. пример
  54. Second
  55. Синтаксис
  56. пример
  57. Синтаксис
  58. пример
  59. Timer
  60. Синтаксис
  61. пример
  62. TimeSerial
  63. Синтаксис
  64. Параметр/Описание
  65. пример
  66. TimeValue
  67. Синтаксис
  68. пример

Функции VBA для работы с датой/временем

    Date () — возвращает текущую системную дату. Установить ее можно при помощи одноименного оператора, например, так:

DateDiff () — возможность получить разницу между датами (опять таки в единицах от лет до секунд).

Dim lDaysCnt As Long lDaysCnt = DateDiff(«d», «20.11.2012», Now) MsgBox «С 20.11.2012 прошло дней: » & lDaysCnt

Первый аргумент определяет период времени, в котором необходимо вернуть разницу между датами. Допустимые значения:
«yyyy» Год
«q» Квартал
«m» Месяц
«y» День года
«d» День
«w» День недели
«ww» Неделя
«h» Час
«n» Минута
«s» Секунда
Наиболее полезна DateDiff при вычислении полных лет. Например, чтобы вычислить сколько лет на текущий момент человеку, в зависимости от даты рождения, можно использовать функцию так:

MsgBox DateDiff(«yyyy», «20.12.1978», Now)

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

MsgBox «Номер недели года: » & DatePart(«ww», Now)

MsgBox DateSerial(2012, 6, 7)

Аналогичным образом (для времени) работают TimeSerial () и TimeValue ()

  • Day (), Year (), Month (), Weekday (), Hour (), Minute (), Second () — специализированные заменители функции DatePart() , которые возвращают нужную часть даты/времени (которую именно — видно из названия).
  • MonthName () — возвращает имя месяца словами по его номеру. Возвращаемое значение зависит от региональных настроек. Если они русские, то вернется русское название месяца.
  • Timer () — возвращает количество секунд, прошедших с полуночи.
  • Источник

    Функции даты-времени в VBA. Работа с датой и временем

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

    Функция возвращает текущую системную дату.

    Синтаксис

    пример

    Добавьте кнопку и добавьте следующую функцию.

    Когда вы выполняете функцию, она производит следующий вывод.

    The Value of a : 19/07/2014

    Функция, которая возвращает текущую системную дату.

    CDate

    Функция преобразует действительное выражение даты и времени для ввода даты.

    Синтаксис

    пример

    Добавьте кнопку и добавьте следующую функцию.

    Когда вы выполняете функцию, она производит следующий вывод.

    The Value of a : 1/01/2020
    The Value of b : 31/12/2050

    Функция, которая преобразует данный вход в дату.

    DateAdd

    Функция, которая возвращает дату, к которой был добавлен указанный временной интервал.

    Синтаксис

    Параметр/Описание

    • Интервал — требуемый параметр. Он может принимать следующие значения.
    • d — день года
    • м — месяц года
    • y — год года
    • yyyy — year
    • w — день недели
    • ww — неделя
    • q — квартал
    • час — час
    • м — минута
    • s — секунда
    • Номер — требуемый параметр. Он может принимать как положительные, так и отрицательные параметры.
    • Дата — требуемый параметр. Вариант или литерал, представляющий дату добавления интервала.

    пример

    Когда вы выполняете вышеуказанную функцию, она производит следующий вывод.

    Line 1 : 27/06/1895
    Line 2 : 27/09/1894
    Line 3 : 27/07/1894
    Line 4 : 28/06/1894
    Line 5 : 28/06/1894
    Line 6 : 28/06/1894
    Line 7 : 4/07/1894
    Line 8 : 1/01/2013 1:00:00 PM
    Line 9 : 1/01/2013 12:01:00 PM
    Line 10 : 1/01/2013 12:00:01 PM
    Line 11 : 27/06/1893
    Line 12 : 27/03/1894
    Line 13 : 27/05/1894
    Line 14 : 26/06/1894
    Line 15 : 26/06/1894
    Line 16 : 26/06/1894
    Line 17 : 20/06/1894
    Line 18 : 1/01/2013 11:00:00 AM
    Line 19 : 1/01/2013 11:59:00 AM
    Line 20 : 1/01/2013 11:59:59 AM

    Функция, которая возвращает дату, к которой был добавлен указанный временной интервал.

    DateDiff

    Функция, которая возвращает разницу между двумя заданными временными интервалами.

    Синтаксис

    Параметр/Описание

    • Интервал — требуемый параметр. Он может принимать следующие значения.
    • d — день года
    • м — месяц года
    • y — год года
    • yyyy — year
    • w — день недели
    • ww — неделя
    • q — квартал
    • час — час
    • м — минута
    • s — секунда
    • Date1 и Date2 — Необходимые параметры.
    • Firstdayofweek — необязательный параметр. Задает первый день недели. Он может принимать следующие значения.
    • 0 = vbUseSystemDayOfWeek — настройка API поддержки национальных языков (NLS)
    • 1 = vbSunday — воскресенье
    • 2 = vbMonday — понедельник
    • 3 = vbTuesday — вторник
    • 4 = vbWednesday — среда
    • 5 = vbThursday — четверг
    • 6 = vbFriday — пятница
    • 7 = vbSaturday — суббота
    • Firstdayofyear — необязательный параметр. Указывает на первый день года. Он может принимать следующие значения.
    • 0 = vbUseSystem — настройка API поддержки национальных языков (NLS)
    • 1 = vbFirstJan1 — начать с недели, в которой происходит 1 января (по умолчанию)
    • 2 = vbFirstFourDays — Начните с недели, которая имеет не менее четырех дней в новом году
    • 3 = vbFirstFullWeek — начните с первой полной недели нового года

    пример

    Добавьте кнопку и добавьте следующую функцию.

    Когда вы выполняете вышеуказанную функцию, она производит следующий вывод.

    Line 1 : 1
    Line 2 : 4
    Line 3 : 12
    Line 4 : 365
    Line 5 : 365
    Line 6 : 52
    Line 7 : 52
    Line 8 : 8783
    Line 9 : 527039
    Line 10 : 31622340

    Функция, которая возвращает разницу между двумя периодами времени.

    DatePart

    Функция, возвращающая определенную часть данной даты.

    Синтаксис

    Параметр/Описание

    • Интервал — требуемый параметр. Он может принимать следующие значения.
    • d — день года
    • м — месяц года
    • y — год года
    • yyyy — year
    • w — день недели
    • ww — неделя
    • q — квартал
    • час — час
    • м — минута
    • s — секунда
    • Date1 — обязательный параметр.
    • Firstdayofweek — необязательный параметр. Задает первый день недели. Он может принимать следующие значения.
    • 0 = vbUseSystemDayOfWeek — настройка API поддержки национальных языков (NLS)
    • 1 = vbSunday — воскресенье
    • 2 = vbMonday — понедельник
    • 3 = vbTuesday — вторник
    • 4 = vbWednesday — среда
    • 5 = vbThursday — четверг
    • 6 = vbFriday — пятница
    • 7 = vbSaturday — суббота
    • Firstdayofyear — необязательный параметр. Указывает на первый день года. Он может принимать следующие значения.
    • 0 = vbUseSystem — настройка API поддержки национальных языков (NLS)
    • 1 = vbFirstJan1 — начать с недели, в которой происходит 1 января (по умолчанию)
    • 2 = vbFirstFourDays — Начните с недели, которая имеет не менее четырех дней в новом году
    • 3 = vbFirstFullWeek — начните с первой полной недели нового года

    пример

    Добавьте кнопку и добавьте следующую функцию.

    Когда вы выполняете вышеуказанную функцию, она производит следующий вывод.

    Line 1 : 1
    Line 2 : 15
    Line 3 : 3
    Line 4 : 1

    Функция, возвращающая указанную часть заданного значения даты ввода.

    DateSerial

    Функция, которая возвращает дату для заданных параметров дня, месяца и года.

    Синтаксис

    Параметр/Описание

    • Год — требуемый параметр. Число от 100 до 9999 или числовое выражение. Значения от 0 до 99 интерпретируются как годы с 1900 по 1999 год. Для всех аргументов за другой год используйте полный четырехзначный год.
    • Месяц — требуемый параметр. Он также может быть в форме выражения, которое должно варьироваться от 1 до 12.
    • День — требуемый параметр. Он также может быть в форме выражения, которое должно варьироваться от 1 до 31.

    пример

    Добавьте кнопку и добавьте следующую функцию.

    Когда вы выполняете вышеуказанную функцию, она производит следующий вывод.

    Функция, которая возвращает действительную дату для данного года, месяца и даты.

    FormatDateTime

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

    Синтаксис

    Параметр/Описание

    • Дата — требуемый параметр.
    • Формат — необязательный параметр. Значение, определяющее формат даты или времени, который будет использоваться. Он может принимать следующие значения.
    • 0 = vbGeneralDate — Default
    • 1 = vbLongDate — дата возврата
    • 2 = vbShortDate — Дата возврата
    • 3 = vbLongTime — возвращает время
    • 4 = vbShortTime — возвращает время

    пример

    Добавьте кнопку и добавьте следующую функцию.

    Когда вы выполняете вышеуказанную функцию, она производит следующий вывод.

    Line 1 : 15/08/2013 8:25:00 PM
    Line 2 : Thursday, 15 August 2013
    Line 3 : 15/08/2013
    Line 4 : 8:25:00 PM
    Line 5 : 20:25

    Функция, которая форматирует дату на основе поставляемых параметров.

    IsDate

    Функция, возвращающая логическое значение, независимо от того, является ли данный ввод датой.

    Синтаксис

    пример

    Добавьте кнопку и добавьте следующую функцию.

    Когда вы выполняете вышеуказанную функцию, она производит следующий вывод.

    Line 1 : True
    Line 2 : True
    Line 3 : True

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

    Функция «День» возвращает число от 1 до 31, которое представляет день указанной даты.

    Синтаксис

    пример

    Добавьте кнопку и добавьте следующую функцию.

    Когда вы выполняете вышеуказанную функцию, она производит следующий вывод.

    Функция, которая возвращает целое число от 1 до 31, которое представляет день указанной даты.

    Month

    Функция Month возвращает число от 1 до 12, которое представляет месяц указанной даты.

    Синтаксис

    пример

    Добавьте кнопку и добавьте следующую функцию.

    Когда вы выполняете вышеуказанную функцию, она производит следующий вывод.

    Функция, которая возвращает целое число от 1 до 12, которое представляет месяц указанной даты.

    Функция Год возвращает целое число, которое представляет год указанной даты.

    Синтаксис

    пример

    Добавьте кнопку и добавьте следующую функцию.

    Когда вы выполняете вышеуказанную функцию, она производит следующий вывод.

    Функция, которая возвращает целое число, которое представляет год указанной даты.

    MonthName

    Функция MonthName возвращает имя месяца для указанной даты.

    Синтаксис

    Параметр Описание

    • Месяц — требуемый параметр. Он определяет номер месяца.
    • Toabbreviate — необязательный параметр. Булевское значение, указывающее, следует ли сокращать имя месяца. Если оставить пустым, значение по умолчанию будет считаться False.

    пример

    Добавьте кнопку и добавьте следующую функцию.

    Когда вы выполняете вышеуказанную функцию, она производит следующий вывод.

    Line 1 : Jan
    Line 2 : January
    Line 3 : Jul
    Line 4 : July

    Функция, которая возвращает имя определенного месяца за указанную дату.

    WeekDay

    Функция WeekDay возвращает целое число от 1 до 7, которое представляет день недели для указанной даты.

    Синтаксис

    Параметр/Описание

      Дата — требуемый параметр. День недели вернет указанную дату. Firstdayofweek — необязательный параметр. Задает первый день недели. Он может принимать следующие значения. 0 = vbUseSystemDayOfWeek — настройка API поддержки национальных языков (NLS) 1 = vbSunday — воскресенье 2 = vbMonday — понедельник 3 = vbВперед — вторник 4 = vbWednesday — среда 5 = vbThursday — четверг 6 = vbFriday — пятница 7 = vbSaturday — суббота

    пример

    Добавьте кнопку и добавьте следующую функцию.

    Когда вы выполняете вышеуказанную функцию, она производит следующий вывод.

    Line 1: 5 Line 2: 4 Line 3: 4 Line 4: 3 Line 5: 4 Line 6: 5

    Функция, которая возвращает целое число (от 1 до 7), которое представляет день недели в течение указанного дня.

    WeekDayName

    Функция WeekDayName возвращает имя дня недели за указанный день.

    • Weekday — требуемый параметр. Номер дня недели.
    • Toabbreviate — необязательный параметр. Булевское значение, указывающее, следует ли сокращать имя месяца. Если оставить пустым, значение по умолчанию будет считаться False.
    • Firstdayofweek — необязательный параметр. Задает первый день недели.
    • 0 = vbUseSystemDayOfWeek — настройка API поддержки национальных языков (NLS)
    • 1 = vbSunday — воскресенье
    • 2 = vbMonday — понедельник
    • 3 = vbTuesday — вторник
    • 4 = vbWednesday — среда
    • 5 = vbThursday — четверг
    • 6 = vbFriday — пятница
    • 7 = vbSaturday — суббота

    пример

    Добавьте кнопку и добавьте следующую функцию.

    Когда вы выполняете вышеуказанную функцию, она производит следующий вывод.

    Line 1 : Tuesday
    Line 2 : Mon
    Line 3 : Sunday
    Line 4 : Tue
    Line 5 : Sunday

    Функция, которая возвращает имя дня недели для указанного дня.

    Функция Now возвращает текущую системную дату и время.

    Синтаксис

    пример

    Добавьте кнопку и добавьте следующую функцию.

    Когда вы выполняете вышеуказанную функцию, она производит следующий вывод. The Value of a : 19/07/2013 3:04:09 PM

    Функция, которая возвращает текущую системную дату и время.

    Функция Hour возвращает число от 0 до 23, которое представляет час дня для указанной отметки времени.

    Синтаксис

    пример

    Добавьте кнопку и добавьте следующую функцию.

    Когда вы выполняете вышеуказанную функцию, она производит следующий вывод.

    Line 1: 15
    Line 2: 23
    Line 3: 14

    Функция, которая возвращает целое число от 0 до 23, которое представляет часовую часть заданного времени.

    Minute

    Функция Minute возвращает число от 0 до 59, которое представляет минуту часа для указанной отметки времени.

    Синтаксис

    пример

    Добавьте кнопку и добавьте следующую функцию.

    Когда вы выполняете вышеуказанную функцию, она производит следующий вывод.

    Line 1: 13
    Line 2: 43
    Line 3: 20

    Функция, возвращающая целое число от 0 до 59, которое представляет минутную часть данного времени.

    Second

    Функция возвращает число от 0 до 59, которое представляет вторую часть часа для указанной отметки времени.

    Синтаксис

    пример

    Добавьте кнопку и добавьте следующую функцию.

    Когда вы выполняете вышеуказанную функцию, она производит следующий вывод. Line 1: 25
    Line 2: 45
    Line 3: 0

    Функция, возвращающая целое число от 0 до 59, которое представляет собой секундную часть данного времени.

    Функция времени возвращает текущее системное время.

    Синтаксис

    пример

    Когда вы выполняете вышеуказанную функцию, она производит следующий вывод.

    Line 1: 3:29:15 PM

    Функция, которая возвращает текущее системное время.

    Timer

    Функция таймера возвращает число секунд и миллисекунд с 12:00.

    Синтаксис

    пример

    Добавьте кнопку и добавьте следующую функцию.

    Когда вы выполняете вышеуказанную функцию, она производит следующий вывод.

    Time is : 19/07/2013 3:45:53 PM
    Timer is: 56753.4

    Функция, которая возвращает число секунд и миллисекунд с 12:00.

    TimeSerial

    Функция TimeSerial возвращает время для указанных часов, минут и вторых значений.

    Синтаксис

    Параметр/Описание

    • Hour — обязательный параметр, который представляет собой целое число от 0 до 23 или любое числовое выражение.
    • Minute — обязательный параметр, который представляет собой целое число от 0 до 59 или любое числовое выражение.
    • Second — обязательный параметр, который представляет собой целое число от 0 до 59 или любое числовое выражение.

    пример

    Добавьте кнопку и добавьте следующую функцию.

    Когда вы выполняете вышеуказанную функцию, она производит следующий вывод.

    8:01:02 PM
    12:59:59 AM
    2:20:18 PM

    Функция, которая возвращает время для конкретного ввода часа, минуты и секунды.

    TimeValue

    Функция TimeValue преобразует заданную входную строку в допустимое время.

    Синтаксис

    пример

    Добавьте кнопку и добавьте следующую функцию.

    Когда вы выполняете вышеуказанную функцию, она производит следующий вывод.

    8:30:00 PM
    5:15:00 AM
    2:30:58 AM

    Функция, которая преобразует входную строку в формат времени.

    Источник

    VBA Date and Time Functions in Excel. VBA Date and Time Functions help us to convert date and time from one format to another. These are DATE, DATEDIFF, DATEPART, DATESERIAL, DATEVALUE, DAY, HOUR, MINUTE, MONTH, NOW, TIME, TIMESERIAL, TIMEVALUE etc. Date & Time functions are Built-In functions. We can use these VBA Date and Time functions in either procedure or function. These functions we use in the VBA editor window in Excel. These Date and Time functions you can use any number of times in VBA macro codes.

    List of Date and Time Functions in Excel VBA:

    Here are the list of Date and Time functions. And also find its description, syntax and return type. We can use these multiple Date and Time functions in one statement.

    Function Description Syntax Return Type
    VBA Date VBA Date function returns current system date. Date() Date
    VBA DateAdd VBA DateAdd function returns a date after which a certain time or date interval has been added. DateAdd(Interval, Number, Date) String
    VBA DateDiff VBA DateDiff function returns the difference between two date values. It depends on the specified interval. DateDiff (Interval,Date1,Date2, FirstDayOfWeek,FirstWeekOfYear) Long
    VBA DatePart VBA DatePart function returns a specified part of a supplied date or time DatePart(interval,date, [firstdayofweek],[firstweekofyear]) Integer
    VBA DateSerial VBA DateSerial function returns date. DateSerial(year, month, day) Date
    VBA DateValue VBA DateValue function returns the date value for specified string input. DateValue(date_value) Date
    VBA Day VBA Day function returns day from date. Day(date_value) Integer
    VBA Hour VBA Hour function returns hour from time. Hour(time_value) Integer
    VBA Minute VBA Minute function returns Minute from time. Minute(time_value Integer
    VBA Month VBA Month function returns month from date. Month(date_value) Integer
    VBA MonthName VBA MonthName function returns a string representing the month given a number from 1 to 12. MonthName(Month,[Abbreviate]) String
    VBA Now VBA Now function returns system date and time. Now() Date
    VBA Time VBA Time function returns current system time. Time() Date
    VBA TimeSerial VBA TimeSerialfunction returns time. TimeSerial(hour, minute, second) Date
    VBA TimeValue VBA TimeValue function returns the date value for specified input represents date. TimeValue(time_value) Date
    VBA Weekday VBA Weekday function returns a number representing the day of the week, given a date value. Weekday(Date,[FirstDayOfWeek]) Integer
    VBA WeekdayName VBA WeekdayName function returns a string representing the day of the week given a number from 1 to 7. WeekdayName(Weekday,[Abbreviate],[FirstDayOfWeek]) String
    VBA Year VBA Year function returns year from date. Year(date_value) Integer

    Other Useful Resources:

    Click on the following links of the useful resources. These helps to learn and gain more knowledge.

    VBA Tutorial VBA Functions List VBA Arrays in Excel Blog

    VBA Editor Keyboard Shortcut Keys List VBA Interview Questions & Answers

    <<Lesson 10>> [Contents] <<Lesson 12>>

    Excel VBA provides various built-in date and time functions that allow us to write VBA codes involving dates and times. We can use date and time functions to display system date and time, add and subtract data and time, converting a string to date and more.

    11.1 Date Functions

    The date functions are explained in Table 11.1.

    Table 11.1 Date and Time Functions

    Function Description
    Now returns current system date and time
    Date returns current system date
    Day(Date) Returns the day of the month for the date specified in the argument
    Weekday(Date) Returns weekday as an integer for the date specified in the argument
    WeekdayName(Weekday(Date)) Returns the name of weekday for the date specified in the argument
    WeekdayName(Weekday(Date), True) Returns the abbreviated name of weekday for the date specified in the argument
    Month(Date) Returns the month of the year in integer for the date specified in the argument
    MonthName(Month(Date)) Returns the name of month of the year for the date specified in the argument
    MonthName(Month(Date)) Returns the abbreviated name of month of the year for the date specified in the argument
    Year(Date) Returns the year in integer for the date specified in the argument

    Example 11.1

    Private Sub CommandButton1_Click()

    Cells(1, 2) = Now
    Cells(2, 2) = Date
    Cells(3, 2) = Day(Date)
    Cells(4, 2) = Weekday(Date)
    Cells(5, 2) = WeekdayName(Weekday(Date))
    Cells(6, 2) = WeekdayName(Weekday(Date), “true”)
    Cells(7, 2) = Month(Date)
    Cells(8, 2) = MonthName(Month(Date))
    Cells(9, 2) = MonthName(Month(Date), “true”)
    Cells(10, 2) = Year(Date)

    End Sub

    The output is as shown in Figure 11.1

    Figure 11.1


    11.2 Time Functions

    The time functions are explained in Table 11.2.

    Table 11.2 Time Functions

    Function Description
    Time Returns the current system time
    Hour Returns the hour from its argument
    Minute Returns the minute from its argument
    Second Returns the second from its argument
    Timer Returns the number of seconds since midnight

    Example 11.2

    Private Sub CommandButton1_Click()

    Cells(1, 2) = Time
    Cells(2, 2) = Hour(Time)
    Cells(3, 2) = Minute(Time)
    Cells(4, 2) = Second(Time)
    Cells(5, 2) = Timer

    End Sub

    The output is shown in Figure 11.2

    Figure 11.2

    11.3 DatePart Function

    The DatePart function returns the part of the date specified in the arguments. The arguments are:

    YYYY- Year
    q- Quarter
    m- Month
    Y- Day of Year
    d- Day
    w- Weekday
    ww- Week
    h- Hour
    n- Minute
    s- Second

    Example 11.3

    Private Sub CommandButton1_Click()

    Cells(1, 2) = DatePart(“YYYY”, Now)
    Cells(2, 2) = DatePart(“q”, Now)
    Cells(3, 2) = DatePart(“m”, Now)
    Cells(4, 2) = DatePart(“y”, Now)
    Cells(5, 2) = DatePart(“d”, Now)
    Cells(6, 2) = DatePart(“w”, Now)
    Cells(7, 2) = DatePart(“ww”, Now)
    Cells(8, 2) = DatePart(“h”, Now)
    Cells(9, 2) = DatePart(“n”, Now)
    Cells(10, 2) = DatePart(“s”, Now)

    End Sub

    The argument Now is to return the current date and time.The output is shown in Figure 11.3

    Figure 11.3

    11.4 DateAdd and DateDiff Functions

    The function DateAdd is to add dates and the DateDiff is the function to subtract dates.

    The syntax of DateAdd is

    DateAdd(“t”,n,date)

    Where t indicates the interval of the part of the date to add, either d(day), m(month) or year and n is the value to add.

    The syntax of DateDiff is

    DateDiff(“t”,date1,date2)

    Where t indicates the interval of the part of the date to subtract. The interval can be YYYY, m, w, ww, d, h, n, s, same as parameters for DatePart. The function of calculating the difference between date1 and date2.

    Example 11.4

    Private Sub CommandButton1_Click()

    Cells(1, 2) = Now
    Cells(2, 2) = DateAdd(“yyyy”, 2, Now)
    Cells(3, 2) = DateAdd(“m”, 10, Now)
    Cells(4, 2) = DateAdd(“d”, 100, Now)
    Cells(5, 2) = DateAdd(“h”, 10, Now)
    Cells(6, 2) = DateAdd(“YYYY”, 3, “2015/3/28”)
    Cells(7, 2) = DateDiff(“YYYY”, Now, “2020/4/16”)
    Cells(8, 2) = DateDiff(“m”, Now, “2020/4/16”)
    Cells(9, 2) = DateDiff(“ww”, Now, “2020/4/16”)
    Cells(10, 2) = DateDiff(“d”, Now, “2020/4/16”)
    Cells(11, 2) = DateDiff(“YYYY”, “2016/5/20”, “2020/4/16”)
    Cells(12, 2) = DateDiff(“m”, “2016/5/20”, “2020/4/16”)

    End Sub

    The output is shown in Figure 11.4

    Figure 11.4

    <<Lesson 10>> [Contents] <<Lesson 12>>

    If you’re working with dates in your excel sheets then you have to understand the date object. By using the date object you could easily process the dates on your excel sheets. You can compare dates to see which one is more recent, you can add and subtract a certain amount of days month, years to a specific date. You can get the current date ….

    You can download the codes and files related to this article here.
    Jump to:

    • DateSerial(), Creating Date Objects From Year, Month and Day Values
    • CDate(), Creating (Converting) Date Objects From Strings
    • IsDate(), Checking if String is a Date Expression
    • Comparing Dates, Recent, Older …
    • Getting The Year, Month and Day Values From A Date Object
    • Adding and Subtracting Years, Months and Days From Dates
    • Date(), Getting Current Date

    DateSerial(), Creating Date Objects From Year, Month and Day Values:

    Using the the DateSerial() function you can create a date object by providing the year, month and day as input. The following code creates a date object for the date April/5/2014 and prints it in cell A2:

    Sub Example1()

    Dim objDate As Date
    'year, month, day
    objDate = DateSerial(2014, 4, 5)

    'prints the result in cell A1 
    Cells(2, 1) = objDate
    End Sub

    CDate(), Creating (Converting) Date Objects From Strings:

    Using the CDate function you can convert a string expression to a Date object. The code below converts the string expression “1/1/2013” to a Date object and prints the results in cell B2:

    Sub Example2()

    Dim objDate As Date
    'A string expression
    objDate = CDate("1/1/2013")

    'prints the result in cell B2
    Cells(2, 2) = objDate
    End Sub

    IsDate(), Checking if String is a Date Expression:

    If the input argument to the CDate() function is not a date expression, you will get an exception. In order to check if a string is a valid date expression you can use the function IsDate(). The code below checks the two strings “Not a Date” and “3/2/2012”, and determines which one is a string expression, and prints the date in cell C2:

    Sub Example3()
    Dim objDate As Date
    Dim strNotDate As String
    Dim strDate As String

    strNotDate = "Not a Date"
    strDate = "3/2/2012"

    If IsDate(strNotDate) = True Then
        'if its a valid date expression print the results in cell C2
        Cells(2, 3) = strNotDate
    Else
        'if its not a date expression show a message box
        MsgBox ("The following string" + vbCr + """" + strNotDate _
        + """" + vbCr + "is not a valid date expression")
       
    End If

    If IsDate(strDate) = True Then
        Cells(2, 3) = strDate
    Else
        MsgBox ("The following string" + vbCr + """" + strDate + """" _
        + vbCr + "is not a valid date expression")
    End If

    End Sub

    Comparing Dates, Recent, Older …

    Once you have created the date object you can compare them using the arithmetic operators <, =, > , <=, >= to see if they are the same  or which is more recent …  The following code takes two date expressions from the cells E2 and E3. Checks if they are valid date expressions, and prints the most recent one in cell E4:

    Sub Example4()
    Dim objDate1 As Date
    Dim objDate2 As Date

    If IsDate(Cells(2, 5)) = True Then
        objDate1 = CDate(Cells(2, 5))
    Else
        MsgBox ("Invalid Input")
        Exit Sub
    End If

    If IsDate(Cells(3, 5)) = True Then
        objDate2 = CDate(Cells(3, 5))
    Else
        MsgBox ("Invalid Input")
        Exit Sub
    End If

    'Note the smaller date is further in the past,
    'there for the larger date would be recent
    If objDate1 < objDate2 Then
        Cells(4, 5) = objDate2
    Else
        Cells(4, 5) = objDate1
    End If

    End Sub

    Getting The Year, Month and Day Values From A Date Object:

    Using the functions Year(), Month(), Day() you can get the year month and day values of the date object. The following example takes the date expression in cell G2 and prints the year, month and day values in cells G3, G4 and G5 respectively:

    Sub Example5()
    Dim objDate As Date

    If IsDate(Cells(2, 7)) = True Then
        objDate = CDate(Cells(2, 7))
    Else
        MsgBox ("Invalid Input")
        Exit Sub
    End If

    'prints the year in cell G3
    Cells(3, 7) = Year(objDate)
    'prints the month in cell G4
    Cells(4, 7) = Month(objDate)
    'prints the day in cell G5
    Cells(5, 7) = Day(objDate)

    End Sub

    Adding and Subtracting Years, Months and Days From Dates:

    Using the DateSerial() function you can add years, months and days to a date object. The code below retrieves the date at cell F2, adds 3 years, 2 month and 5 days to it and prints the result in cell F3:

    Sub Example6()
    'the input date object
    Dim objDate As Date
    'the new date object
    Dim objNewDate As Date
    'the year value in the input date object
    Dim intYear As Integer
    'the month value in the input date object
    Dim intMonth As Integer
    'the day value in the input date object
    Dim intDay As Integer

    If IsDate(Cells(2, 9)) = True Then
        objDate = CDate(Cells(2, 9))
    Else
        MsgBox ("Invalid Input")
        Exit Sub
    End If

    intYear = Year(objDate)
    intMonth = Month(objDate)
    intDay = Day(objDate)

    'create the new date object with +3 year, +2 months and +5 days
    objNewDate = DateSerial(intYear + 3, intMonth + 2, intDay + 5)

    Cells(3, 9) = objNewDate

    End Sub

    Date(), Getting Current Date:

    The function Date() returns the current date based on the computers calendar:

    Sub Example7()
    Dim objDate As Date

    'gets the current date based on the computers calendar
    objDate = Date
    MsgBox (objDate)
    End Sub

    You can download the codes and files related to this article here.

    If you need assistance with your code, or you are looking to hire a VBA programmer feel free to contact me. Also please visit my website  www.software-solutions-online.com

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