Vba excel date функция

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

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

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

VBA Date

Excel VBA Date

There are some functions which are really very handy, and we choke our life without those functions being a VBA user. DATE function is one of those functions which can be really very useful at times and can make life easier for a programmer. In an Excel spreadsheet, there is a function called TODAY() which gives the current date as a result based on the system date. On similar lines, VBA has DATE function which gives current date based on the system date.

The VBA DATE function returns the current date based on system date as a result and has really very simple syntax.

This function does not have any argument to be passed comes with the name of the function and empty parentheses. It is not mandatory to add the parentheses as well while calling this function. Isn’t this function really simple in nature?

The syntax of DATE function in VBA.

Syntax of DATE

How to Use Excel VBA Date Function?

We will learn how to use a VBA Date function with few examples in excel.

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

VBA Date Function – Example #1

Suppose, you wanted to see the current date in MsgBox. How can you do that? Just follow the steps below and you’ll be through.

Step 1: Insert a new module in your Visual Basic Editor.

Example 1

Step 2: Define a sub-procedure to write create and save a macro.

Code:

Sub DateEx1()

End Sub

VBA Date Example 1-2

Step 3: Define a variable named CurrDate which can hold the value of the current date. Since, we are about to assign a date value to the variable, make sure you are defining it as a date.

Code:

Sub DateEx1()

Dim CurrDate As Date

End Sub

VBA Date Example 1-3

Step 4: Using the assignment operator, assign a value of the current system date to the variable newly created. You just need to add DATE in order to assign the date value. Use the following piece of code:

Code:

Sub DateEx1()

Dim CurrDate As Date

CurrDate = Date

End Sub

VBA Date Example 1-4

Step 5: Use MsgBox to be able to see the current system date under Message Box prompt. Use the line of code given below:

Code:

Sub DateEx1()

Dim CurrDate As Date

CurrDate = Date

MsgBox "Today's Date is: " & CurrDate

End Sub

VBA Date Example 1-5

Step 6: Hit F5 or run button manually to Run this code. You’ll be able to see a Message Box as shown in below screenshot with the current date.

Result of Example 1

Note that, the date shown here in the screenshot is the date I have run this script at. You may be getting a different date at the time you run this code, based on your system date.

This is the simplest example of getting the current date. You can also use Cells.Value function to get the date value in a particular cell of your excel sheet.

VBA Date Function – Example #2

Home Loan EMI payment due date

Suppose I have a worksheet and I need a system to show me a message “Hey! You need to pay your EMI today.” Every time I open my sheet and the value in cell A1 is the current system date. Let’s see step by step how we can do that.

Step 1: Insert a new module and define a new sub-procedure named auto_open() to create a macro. auto_open() allows your macro to run automatically every time you open the worksheet.

Code:

Sub auto_open()

End Sub

VBA Date Example 2-1

Step 2: Use If condition to assign the value of the current date in cell A1 of worksheet HomeLoan_EMI.

Code:

Sub auto_open()

If Sheets("HomeLoan_EMI").Range("A1").Value = Date

End Sub

VBA Date Example 2-2

Step 3: Now, use Then on the same line after IF so that we can add a statement which will execute as long as if-condition is true.

Code:

Sub auto_open()

If Sheets("HomeLoan_EMI").Range("A1").Value = Date Then

End Sub

VBA Date Example 2-3

Step 4: Add a statement to be executed for the condition which is true.

Code:

Sub auto_open()

If Sheets("HomeLoan_EMI").Range("A1").Value = Date Then

MsgBox ("Hey! You need to pay your EMI today.")

End Sub

VBA Date Example 2-4

This statement will pop-up under Message Box as soon as the If a condition is true.

Step 5: As we know, every IF condition always needed an Else condition. Add an Else condition to this loop.

Code:

Sub auto_open()

If Sheets("HomeLoan_EMI").Range("A1").Value = Date Then

MsgBox ("Hey! You need to pay your EMI today.")

Else

Exit Sub

End Sub

VBA Date Example 2-5

This else condition will terminate the automatic opening of Macro if a date in cell A1 is not the current system date.

Step 6: Finally, End the IF loop by using statement End IF.

Code:

Sub auto_open()

If Sheets("HomeLoan_EMI").Range("A1").Value = Date Then

MsgBox ("Hey! You need to pay your EMI today.")

Else

Exit Sub

End If

End Sub

VBA Date Example 2-6

Step 7: This is it, now every time you open your worksheet the system will automatically run the above code and see if the date value in cell A1 is your EMI due date or not. If the EMI due date equals to the system date, it will show the message as below:

Result of Example 2

VBA Date Function – Example #3

VBA Date to Find out the Credit Card Bill Payee

Suppose I have a list of customers who have a credit card and you want to know who has payment due today. So that you can call them and ask them to pay their due immediately by EOD.

Example 3

VBA Date could be handy in allowing you to automate the things instead of checking the dates one by one. Let’s see how to do this step by step:

Step 1: Define a New macro using a sub-procedure under a module.

Code:

Sub DateEx3()

End Sub

VBA Date Example 3-2

Step 2: Define two new variables one of which will be useful in looping the code up and another one in order to hold the value of the current system date.

Code:

Sub DateEx3()
Dim DateDue As Date
Dim i As Long
DateDue = Date
i = 2
End Sub

VBA Date Example 3-3

Step 3: Now use the following piece of code which helps in searching the person who has a credit card bill due date as the current system date. This code allows checking the Customer who has bill payment due on the current system date along with the bill amount.

Code:

Sub DateEx3()
Dim DateDue As Date
Dim i As Long
DateDue = Date
i = 2
For i = 2 To Sheets("CC_Bill").Cells(Rows.Count, 1).End(xlUp).Row
If DateDue = DateSerial(Year(DateDue), Month(Sheets("CC_Bill").Cells(i, 3).Value), 
Day(Sheets("CC_Bill").Cells(i, 3).Value)) Then
MsgBox "Customer Name : " & Sheets("CC_Bill").Cells(i, 1).Value & vbNewLine 
& "Premium Amount : " & Sheets("CC_Bill").Cells(i, 2).Value
End If
Next i
End Sub

VBA Date Example 3-4

Step 4: Run this code by hitting F5 or Run button manually and see the output.

VBA Date Example 3-5

On the first iteration, we can see that Mohan is the one who has Bill of 12,900 due on 29-Apr-2019 (Current system date on which this code is run). If we hit OK, we can see the next customer name who has a bill due on 29-Apr-2019 (Rajani is the next).

Result of Example 3-1

This code will really be handy when you are having millions of rows of customers who have their bill due on one particular day. Please note that all the scripts mentioned in this article are run on 29-Apr-2019. You might get different date value when you run this sample codes based on the system date.

Result of Example 3-2

Things to Remember

  • VBA DATE function returns the current system date and as parallel to Excel’s TODAY() function.
  • VBA DATE function does not have any argument to be passed in excel. Doesn’t even need the parentheses to be called while using this function in the code.
  • VBA DATE is a non-volatile function in excel.
  • VBA stores Date values as DATE at the time of execution. So, does not define a variable holding value as a String/Integer. It will cause an error during execution of the code.

Recommended Articles

This has been a guide to Excel VBA Date. Here we have discussed how to use Excel VBA Date Functions along with practical examples and downloadable excel template. You can also go through our other suggested articles –

  1. VBA Date Format
  2. VBA GoTo
  3. VBA RGB
  4. VBA DateSerial

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

You are free to use this image on your website, templates, etc, Please provide us with an attribution linkArticle Link to be Hyperlinked
For eg:
Source: VBA Date Function (wallstreetmojo.com)

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 excel currentregion rows count
  • Vba excel createobject wscript shell run
  • Vba excel countifs примеры
  • Vba excel countif пример
  • Vba excel count rows in range