Excel vba день месяц год

Функции для работы с датой и временем в 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 Первая полная неделя года.

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.

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

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

  • 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() — возвращает количество секунд, прошедших с полуночи.

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

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

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

Функции VBA даты и времени

Date() – позволяет получить значение текущей даты, установленной в системе.

Time() – вернет установленное в системе время

Now() – комбинированная функция, так как она позволяет получить значение системной даты и времени.

DateAdd(интервал, число, дата) – позволяет прибавить к заданной дате (параметр “дата”) указанное количество лет, кварталов, месяцев или секунд. На выходе мы получим следующее значение: дата + (число * интервал).

DateDiff(интервал, дата, дата2) – позволяет получить разницу между заданными датами, например. В годах, месяцах и так далее, разница определяется параметром “интервал”.

DatePart(интервал, дата) – позволяет получить заданную часть даты, например, только значение года, месяца или дня недели. Результат возврата регулируется параметром “интервал”.

DateSerial(год, месяц, день) – данная функция vba принимает три числовые значения, по которым возвращается дата.

DateValue(строка) – аналог предыдущей функции, но тут в качестве параметра мы передаем не числа. А строковое значение, на основе которого будет возвращаться дата, vba работа с датами.

Day(дата) – позволяет получить значение текущего дня (если отсутствует параметр “дата”) или для заданной даты.

Year(дата) – позволяет получить значение текущего года (если отсутствует параметр “дата”) или для заданной даты.

Month(дата) – позволяет получить значение текущего месяца (если отсутствует параметр “дата”) или для заданной даты.

Weekday(дата) – позволяет получить значение текущей недели (если отсутствует параметр “дата”) или для заданной даты.

Hour(время) – позволяет получить текущее значение часов (если отсутствует параметр “время”) или для заданного времени, vba дата и время.

Minute(время) – позволяет получить текущее значение минут (если отсутствует параметр “время”) или для заданного времени.

Second(время) – позволяет получить текущее значение секунд (если отсутствует параметр “время”) или для заданного времени.

Timer() – удобная функция для определения промежутка времени, ушедшего на выполнение заданного блока кода. Сама функция возвращает целое количество секунд, которые прошли начиная с полуночи.

TimeSerial(часы, минуты, секунды) – позволяет получить время, заданное тремя параметрами

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

MonthName(числовое значение) – VBA функция позволяет получить название месяца, в качестве параметра указываем номер месяца.

WeekDay(дата) — задает возвращает имя месяца словами по его номеру. Возвращаемое значение зависит от региональных настроек. Если они русские, то вернется русское название месяца.

Помимо указанных выше vba функций даты и времени, можно использовать и такие вариации:

Date (дата) – позволяет задать системную дату

Time (время) – позволяет задать системное время.

В приведенных выше функциях даты и времени vba языка используется параметр “интервал”, который может принимать следующие значения:

  • w – недели
  • q – квартал
  • d – месяца
  • y – года

VBA функции форматирование данных

Для форматирования данных в языке VBA используется функция Format, которая позволяет сформировать данные любого встроенного типа, используя заданный образец. Общий синтаксис функции format:

Format(Выражение, [“формат”, [первый день недели, [первая неделя года]]]) – тут параметр “выражение” является любым допустимым значением. Формат – необязательный параметр, который задает формат данных, должен заключаться в кавычки. Остальные два параметра также являются необязательными, и задают день недели, который нужно считать первым, и первую неделю года.

Параметр формат может принимать следующие значения:

  • General Number – числовое значение без выделения разрядов тысяч, например, 12150,2003
  • Currency – денежный формат, выделяются тысячные разряды и два знака после запятой, например, 255,33р.
  • Fixed – числовое значение без выделения разрядов тысяч и двумя знаками после запятой, например, 22439,12.
  • Standart – числовое значение, которое умножается на 100, при этом, остаются два знака после запятой и символ процента, например, 55,63%.
  • Scientific – числовой формат для научных вычисление, например, 5,23Е+03
  • Yes/No – данный параметр определяет, что функция вернет “Да” если форматированное выражение содержит строку Нет, или ненулевое значение и “Нет” в противном случае.
  • True/False – аналог предыдущего параметра, но для строк “Истина” и “Ложь”.
  • On/Off – для строк вида “Вкл” и “Выкл”.
  • General Date – форматирование выражения в соответствии с установленными в системе стандартами даты и времени, например, 10.11.02 12:25:50
  • Long Date – вывод полного формата даты, в зависимости от установок в системе, например, 10 октября 2013 г, vba функции даты.
  • Medium Date – средний формат дат, например, 10-Окт-13.
  • Short Date – короткий вывод формата даты, например, 10.10.13.
  • Long Time – вывод в формате времени (часы, минуты, секунды), например, 12:20:40.
  • Medium Time – 12 часовой формат времени (часы, минуты), например, 05:30.
  • Short Time — 24 часовой формат времени (часы, минуты), например, 17:30.

<<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>>

VBA Date is a Date and Time function. Therefore, it returns only the current date as per your system date. Also, the important thing to note is that this function has no arguments whatsoever. Therefore, another important factor is that this function returns the current system date.

In Excel, we cannot live without some of the functions, and “VBA Date” is one of those functions. In addition, if you are a frequent user of an Excel worksheet, then you must be aware of a function called “TODAY (),” which will return the current date as per the system date.

The Date function is simple. It returns only the current date per the system date you are using. It works similar to our worksheet function “TODAY” but not volatile in nature.

The syntax of the excel DATE functionThe date function in excel is a date and time function representing the number provided as arguments in a date and time code. The result displayed is in date format, but the arguments are supplied as integers.read more is very simple because it has no argument to supply and includes only empty parenthesis.

Date ()

Parenthesis is available to explain the function when you use the function. No need to enter parenthesis.

Table of contents
  • Excel VBA DATE Function
    • How to use Excel VBA Date Function?
      • Example #1
      • Example #2
      • Example #3
    • Recommended Articles

VBA Date Function

How to use Excel VBA Date Function?

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

Example #1

Assume you want to insert the current date in cell A1 then follow the below steps to write the code to insert the current date in cell A1.

Step 1: Create a macro name.

Code:

Sub Date_Example1()

VBA Date Function Example 1

Step 2: Since we need to store the current date in cell A1 our code will be Range (“A1”).Value.

Code:

Sub Date_Example1()
Range("A1").Value
End Sub

VBA Date Function Example 1-1

Step 3: In cell A1 we need the current date, so use the Date function.

Code:

Sub Date_Example1()
Range("A1").Value = Date
End Sub

VBA Date Function Example 1-1

Step 4: We have completed it now. Let us run this code now by pressing the F5 key, or we can also run the code manually, as shown in the below screenshot. We will get the current date in cell A1.

VBA Date Function Example 1-2

So, when writing the code, the current date in the system is “15th March 2019.”

Note: The format of your date depends on your windows settings. Anyway, you can change the format of the date under format cells.

Example #2

Assume you are a LIC agent and have several customers to deal with. One of the key objects is to know whose payment is due today so that you can call them and collect the payment immediately.

Assume below the list of customers you have in the database.

VBA Date Function Example 2-1

We have already written a code that will notify us as soon as we open the Excel file.

Code:

Sub Due_Notifier()
  Dim Duedate As Date
  Dim i As Long

  Duedate = Date
  i = 2

For i = 2 To Cells(Rows.Count, 1).End(xlUp).Row
  If Duedate = DateSerial(Year(Date), Month(Cells(i, 3).Value), Day(Cells(i, 3).Value)) Then
    MsgBox "Customer Name : " & Cells(i, 1).Value & vbNewLine & "Premium Amount : " & Cells(i, 2).Value
  End If
Next i

End Sub

Please copy the above code and paste it into the VBA module.

VBA Date Function Example 2-2.pn

Now, double-click on the “This Workbook” option.

VBA Date Function Example 2-3

Now, select “Workbook” from the above dropdown.

VBA Date Function Example 2-4

When you select the option “Workbook,” you can see a private macro automatically opens.

VBA Date Function Example 2-5

Here, the macro name says “Workbook_Open ()”; whenever this workbook opens, what you have to do. Whenever this workbook opens, we need to run the macro we have created.

So, here we need to call the macro we have created by its name. For example, in the above code, our macro name is “Due_Notifier.”

Code:

Call Due_Notifier

Example 2-6

Now save this workbook and close it.

After closing it, open the workbook and see the magic.

Now, we will open.

Example 2-7

It shows the customer’s name and due amount for the current date.

The “Customer Name” is “Amar,” and the due amount is “20,883”. It is showing this customer name because the due date for Mr. Amar is 15th March 2019, i.e., today.

Now, click on “OK.” It will show other customer names if the due date is on today.

Example 2-8

It shows Mr. Arvind’s name; his due date is also 15th March 2019.

You can easily identify the customer names as soon as you come to the office. One of the big headaches is gone.

Similarly, we have created one more excel macroA macro in excel is a series of instructions in the form of code that helps automate manual tasks, thereby saving time. Excel executes those instructions in a step-by-step manner on the given data. For example, it can be used to automate repetitive tasks such as summation, cell formatting, information copying, etc. thereby rapidly replacing repetitious operations with a few clicks.
read more
, to send auto birthday emails from your Outlook.

Example #3

Assume you are in an “Employee Engagement Team,” and you are responsible for sending birthday emails to your employees. Unfortunately, identifying and sending the email to everyone separately is a painful job.

Hello, my dear friend, don’t worry. We have created a macro for you to send the auto birthday emails to your employees.

We have created some data to test. Below is the image of the same.

Example 3

We must update the employee master according to the table’s headings. Below is the code to send the emails.

Please copy the below code and paste it into the module.

Sub Birthday_Wishes()

Dim OutlookApp As Outlook.Application
Dim OutlookMail As Outlook.MailItem
Dim Mydate As Date
Dim i As Long

Set OutlookApp = New Outlook.Application
Mydate = Date
i = 2

For i = 2 To Cells(Rows.Count, 1).End(xlUp).Row
Set OutlookMail = OutlookApp.CreateItem(olMailItem)

If Mydate = DateSerial(Year(Date), Month(Cells(i, 5).Value), Day(Cells(i, 5).Value)) Then
OutlookMail.To = Cells(i, 7).Value
OutlookMail.CC = Cells(i, 8).Value
OutlookMail.BCC = ""
OutlookMail.Subject = "Happy Birthday - " & Cells(i, 2).Value
OutlookMail.Body = "Dear " & Cells(i, 2).Value & "," & vbNewLine & vbNewLine & _
"We wish you a happy birhday on behalf of the management and we wish all the success in the coming future" & vbNewLine & _
vbNewLine & "Regards," & vbNewLine & "StrIDE Team"
OutlookMail.Display
OutlookMail.Send

End If
Next i

End Sub

Open the file and run this code when you come to the office. It will automatically send birthday wishes to the respective email IDs.

Note: You should have Outlook configured in your system.

Recommended Articles

This article is a guide to VBA Date Function. Here, we learn how to use VBA’s Date function and some simple to advanced examples. We also saw one of the projects where we created one macro that sends auto birthday emails from your Outlook. Below are some useful Excel articles related to VBA: –

  • DateSerial in VBA
  • VBA Select Case
  • CDATE Function in VBA
  • VBA Send Email from Excel

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

Понравилась статья? Поделить с друзьями:
  • Excel vba двухсторонняя печать
  • Excel vba двойные кавычки
  • Excel vba два знака после запятой
  • Excel vba дата сохранения файла
  • Excel vba дата изменения файла