Vba excel если дата между

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

Функция Date

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

Синтаксис

Пример

Sub PrimerDate()

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

End Sub

Функция DateAdd

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

Синтаксис

DateAdd(interval, number, date)

Параметры

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

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

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

Пример

Sub PrimerDateAdd()

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

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

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

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

End Sub

Функция DateDiff

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

Синтаксис

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

Параметры

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

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

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

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

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

Пример

Sub PrimerDateDiff()

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

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

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

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

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

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

End Sub

Функция DatePart

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

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

Синтаксис

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

Параметры

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

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

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

Пример

Sub PrimerDatePart()

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

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

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

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

End Sub

Функция DateSerial

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

Синтаксис

DateSerial(year, month, day)

Параметры

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

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

Пример

Sub PrimerDateSerial()

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

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

End Sub

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

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

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

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

Функция DateValue

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

Синтаксис

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

Пример

Sub PrimerDateValue()

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

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

End Sub

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

Функция Day

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

Синтаксис

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

Пример

Sub PrimerDay()

    MsgBox Day(Now)

End Sub

Функция IsDate

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

Синтаксис

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

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

Пример

Sub PrimerIsDate()

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

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

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

End Sub

Функция Hour

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

Синтаксис

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

Пример

Sub PrimerHour()

    MsgBox Hour(Now)

    MsgBox Hour(«22:36:54»)

End Sub

Функция Minute

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

Синтаксис

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

Пример

Sub PrimerMinute()

    MsgBox Minute(Now)

    MsgBox Minute(«22:36:54»)

End Sub

Функция Month

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

Синтаксис

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

Пример

Sub PrimerMonth()

    MsgBox Month(Now)

End Sub

Функция MonthName

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

Синтаксис

MonthName(month, [abbreviate])

Параметры

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

Пример

Sub PrimerMonthName()

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

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

End Sub

Функция Now

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

Синтаксис

Пример

Sub PrimerNow()

    MsgBox Now

    MsgBox Day(Now)

    MsgBox Hour(Now)

End Sub

Функция Second

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

Синтаксис

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

Пример

Sub PrimerSecond()

    MsgBox Second(Now)

    MsgBox Second(«22:30:14»)

End Sub

Функция Time

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

Синтаксис

Пример

Sub PrimerTime()

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

End Sub

Функция TimeSerial

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

Синтаксис

TimeSerial(hour, minute, second)

Параметры

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

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

Пример

Sub PrimerTime()

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

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

End Sub

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

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

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

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

Функция TimeValue

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

Синтаксис

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

Пример

Sub PrimerTimeValue()

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

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

End Sub

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

Функция Weekday

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

Синтаксис

Weekday(date, [firstdayofweek])

Параметры

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

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

Пример

Sub PrimerWeekday()

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

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

End Sub

Функция WeekdayName

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

Синтаксис

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

Параметры

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

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

Пример

Sub PrimerWeekdayName()

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

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

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

End Sub

Функция Year

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

Синтаксис

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

Пример

Sub PrimerYear()

    MsgBox Year(Now)

End Sub

Приложение 1

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

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

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

Приложение 2

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

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

Приложение 3

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

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

Thank you to @RonRosenfeld for his answer in the comments on the question. Here is the corrected code which works. Added code that also shows an error message if the date doesn’t validate by changing text color on the User Form from blending into the background to being red.

Changes Explained:

The first changes made was to declare what type of variable tempDate, oldDate, and lateDate were. Before, not having them declared made them Variant. This insures that they are recorded as a date type and thus can be compared as I was trying to do.

So:

Dim tempDate
Dim oldDate
Dim lateDate

Becomes:

Dim tempDate As Date
Dim oldDate As Date
Dim lateDate As Date

The second change is moving the IsDate() to its own If statement. This is due to the fact that if the inputted text was not a date, it would cause a fatal error before even reaching the other If statement as it was trying to save a non-date to a variable of date type. So tempDate = weekInput.Value became:

If IsDate(weekInput.Value) Then
    tempDate = weekInput.Value
End If

The rest remained the same. Except I deleted the MsgBox and made a nicer, less obtrusive error message by changing the color of an error message from blending into the background to being red by adding these lines of code:

dateError.ForeColor = &H80000004
dateError.ForeColor = &HFF&

Answer:

Here is the full code:

Private Sub weekInput_Exit(ByVal Cancel As MSForms.ReturnBoolean)
    Dim tempDate As Date
    Dim oldDate As Date
    Dim lateDate As Date

    If IsDate(weekInput.Value) Then
        tempDate = weekInput.Value
    End If

    oldDate = Date - 365
    lateDate = Date + 365

    If tempDate >= oldDate And tempDate <= lateDate Then
        weekPicker.Value = weekInput.Value
        dateError.ForeColor = &H80000004
    Else
        weekInput.Value = weekPicker.Value
        dateError.ForeColor = &HFF&
    End If
End Sub

Содержание

  1. DateDiff function
  2. Syntax
  3. Settings
  4. Remarks
  5. Example
  6. See also
  7. Support and feedback
  8. Функция DateDiff
  9. Синтаксис
  10. Параметры
  11. Примечания
  12. Пример
  13. См. также
  14. Поддержка и обратная связь

DateDiff function

Returns a Variant (Long) specifying the number of time intervals between two specified dates.

Syntax

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

The DateDiff function syntax has these named arguments:

Part Description
interval Required. String expression that is the interval of time you use to calculate the difference between date1 and date2.
date1, date2 Required; Variant (Date). Two dates you want to use in the calculation.
firstdayofweek Optional. A constant that specifies the first day of the week. If not specified, Sunday is assumed.
firstweekofyear Optional. A constant that specifies the first week of the year. If not specified, the first week is assumed to be the week in which January 1 occurs.

Settings

The interval argument has these settings:

Setting Description
yyyy Year
q Quarter
m Month
y Day of year
d Day
w Weekday
ww Week
h Hour
n Minute
s Second

The firstdayofweek argument has these settings:

Constant Value Description
vbUseSystem 0 Use the NLS API setting.
vbSunday 1 Sunday (default)
vbMonday 2 Monday
vbTuesday 3 Tuesday
vbWednesday 4 Wednesday
vbThursday 5 Thursday
vbFriday 6 Friday
vbSaturday 7 Saturday

The firstweekofyear argument has these settings:

Constant Value Description
vbUseSystem 0 Use the NLS API setting.
vbFirstJan1 1 Start with week in which January 1 occurs (default).
vbFirstFourDays 2 Start with the first week that has at least four days in the new year.
vbFirstFullWeek 3 Start with first full week of the year.

Use the DateDiff function to determine how many specified time intervals exist between two dates. For example, you might use DateDiff to calculate the number of days between two dates, or the number of weeks between today and the end of the year.

To calculate the number of days between date1 and date2, you can use either Day of year («y») or Day («d»). When interval is Weekday («w»), DateDiff returns the number of weeks between the two dates. If date1 falls on a Monday, DateDiff counts the number of Mondays until date2. It counts date2 but not date1.

If interval is Week («ww»), however, the DateDiff function returns the number of calendar weeks between the two dates. It counts the number of Sundays between date1 and date2. DateDiff counts date2 if it falls on a Sunday; but it doesn’t count date1, even if it does fall on a Sunday.

If date1 refers to a later point in time than date2, the DateDiff function returns a negative number. The firstdayofweek argument affects calculations that use the «w» and «ww» interval symbols.

If date1 or date2 is a date literal, the specified year becomes a permanent part of that date. However, if date1 or date2 is enclosed in double quotation marks (» «), and you omit the year, the current year is inserted in your code each time the date1 or date2 expression is evaluated. This makes it possible to write code that can be used in different years.

When comparing December 31 to January 1 of the immediately succeeding year, DateDiff for Year («yyyy») returns 1 even though only a day has elapsed.

For date1 and date2, if the Calendar property setting is Gregorian, the supplied date must be Gregorian. If the calendar is Hijri, the supplied date must be Hijri.

Example

This example uses the DateDiff function to display the number of days between a given date and today.

See also

Support and feedback

Have questions or feedback about Office VBA or this documentation? Please see Office VBA support and feedback for guidance about the ways you can receive support and provide feedback.

Источник

Функция DateDiff

Возвращает значение типа Variant (Long), указывающее на количество интервалов времени между двумя указанными датами.

Синтаксис

DateDiff(интервал, дата1, дата2, [ первый_день_недели, [ первая_неделя_года ]] )

Синтаксис функции DateDiff использует следующие именованные аргументы:

Часть Описание
интервал Обязательный аргумент. Строковое выражение, которое обозначает интервал времени, используемый для вычисления разницы значений дата1 и дата2.
дата1, дата2 Обязательный элемент; Variant (Date). Две даты, которые требуется использовать в расчете.
первый_день_недели Необязательный аргумент. Константа, задающая первый день недели. Если она не указана, им является воскресенье.
первая_неделя_года Необязательно. Константа, задающая первую неделю года. Если она не указана, первой неделею является неделя, начинающаяся 1 января.

Параметры

Аргументinterval имеет следующие параметры:

Setting Описание
yyyy Год
q Квартал
m Месяц
y День года
d День
w День недели
ww Неделя
h Часы
n Минуты
s Секунды

Аргумент первый_день_недели может принимать следующие значения:

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

Аргумент firstweekofyear имеет следующие параметры:

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

Примечания

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

Для вычисления числа дней между аргументами дата1 и дата2 используется значение «День года» («y») или «День» («d»). Если интервал задан как «День недели» («w»), DateDiff возвращает число недель между двумя датами. Если день дата1 приходится на понедельник, DateDiff считает число понедельников до дня дата2. День, соответствующий значению аргумента дата2, учитывается, а дата1 — нет.

Однако если интервал задан как «Неделя» («ww»), функция DateDiff возвращает число календарных недель между двумя датами. Для этого рассчитывается число воскресений между днями дата1 и дата2. DateDiff учитывает день дата2, если он приходится на воскресенье; день дата1 не учитывается, даже если он приходится на воскресенье.

Если значение дата1 соответствует более поздней дате, чем значение дата2, функция DateDiff возвращает отрицательное число. Аргумент первый_день_недели влияет на вычисления, если заданы значения «w» и «ww».

Если аргумент дата1 или дата2 содержит литерал даты, указанный год становится постоянной частью этой даты. Однако если аргумент дата1 или дата2 заключен в двойные кавычки (» «), а год опущен, при каждом вычислении выражения дата1 или дата2 в код вставляется текущий год. Это позволяет писать код, который можно использовать для разных лет.

При сравнении 31 декабря с 1 января следующего года функция DateDiff для года («yyyy») возвращает значение 1, не смотря на то, что разница составляет всего один день.

Если в свойстве Calendar задан григорианский календарь, аргументы дата1 и дата2 следует указывать соответствующим образом. Если используется календарь Хиджра, дата должна соответствовать ему.

Пример

В данном примере функция DateDiff отображает число дней между указанной датой и сегодняшним днем.

См. также

Поддержка и обратная связь

Есть вопросы или отзывы, касающиеся Office VBA или этой статьи? Руководство по другим способам получения поддержки и отправки отзывов см. в статье Поддержка Office VBA и обратная связь.

Источник

VBA DateDiff function in Excel is categorized as a Date & Time function. This is a built-in Excel VBA Function. This function returns the difference between two date values, based on the interval specified. We can use this function in VBA and can’t use in Excel.

This function we use in either procedure or function in a VBA editor window in Excel. We can use this VBA DateDiff Function in any number of times in any number of procedures or functions. Let us learn what is the syntax and parameters of the DateDiff function, where we can use this DateDiff Function and real-time examples in Excel VBA.

Table of Contents:

  • Objective
  • Syntax of VBA DateDiff Function
  • Parameters or Arguments
  • Where we can apply or use VBA DateDiff Function?
  • Example 1: Compute the number of days
  • Example 2: Compute the number of months
  • Example 3: Compute the number of years
  • Example 4: Compute the number of weeks
  • Example 5: Compute the number of hours
  • Instructions to Run VBA Macro Code
  • Other Useful Resources

The syntax of the DateDiff Function in VBA is

DateDiff(Interval,Date1,Date2,[FirstDayOfWeek],[FirstWeekOfYear])

The DateDiff function returns a string value.

Parameters or Arguments:

The DateDiff function has five arguments in Excel VBA.
where
Interval:The Interval is a required argument. It represents the interval of time to calculate the difference between two Date1 and Date2. Here is a list of interval values.

Interval Description
yyyy Year
q Quarter
m Month
y Day of year
d Day
w Weekday
ww Week
h Hour
n Minute
s Second

Date1:The Date1 is a required argument. It represents date.
Date2:The Date2 is a required argument. It represents date.
[FirstDayOfWeek]:The [FirstDayOfWeek] is an optional constant argument. It represents the first day of the week. If this argument is ignored, Sunday(vbSunday) is the default value.

VB Constant Value Description
vbUseSystem 0 Use the National Language Support(NLS) API setting
vbSunday 1 Sunday (default)
vbMonday 2 Monday
vbTuesday 3 Tuesday
vbWednesday 4 Wednesday
vbThursday 5 Thursday
vbFriday 6 Friday
vbSaturday 7 Saturday

[FirstWeekOfYear]:The [FirstWeekOfYear] is an optional constant argument. It represents the first week of the year. If this argument is ignored, 1st Jan(vbFirstJan1) is the default value.

VB Constant Value Description
vbUseSystem 0 Use the National Language Support(NLS) API setting
vbFirstJan1 1 The week in which January 1 occurs (default)
vbFirstFourDays 2 The first week consists at least four days in the year
vbFirstFullWeek 3 The first full week of the year

Where we can apply or use VBA DateDiff Function?

We can use this DateDiff Function in VBA MS Office 365, MS Excel 2016, MS Excel 2013, 2011, Excel 2010, Excel 2007, Excel 2003, Excel 2016 for Mac, Excel 2011 for Mac, Excel Online, Excel for iPhone, Excel for iPad, Excel for Android tablets and Excel for Android Mobiles.

Example 1: Compute the number of days between a start date and end date

Here is a simple example of the VBA DateDiff function. This below example computes the number of days between a start date and end date.

'Compute the number of days between a start date and end date
Sub VBA_DateDiff_Function_Ex1()

    'Variable declaration
    Dim sDate As Date
    Dim eDate As Date
    Dim iDate As Integer
            
    sDate = "02/04/2018"
    eDate = "04/06/2018"
    
    iDate = DateDiff("d", sDate, eDate)
        
    MsgBox "The number of days between " & sDate & " and " & eDate & " : " & iDate, vbInformation, "VBA DateDiff Function"
    
End Sub

Output: Here is the screen shot of the first example output.
VBA DateDiff Function

Example 2: Compute the number of months between a start date and end date

Let us see one more example of the VBA DateDiff function. This below example computes the number of months between a start date and end date.

'Compute the number of months between a start date and end date
Sub VBA_DateDiff_Function_Ex2()

    'Variable declaration
    Dim sDate As Date
    Dim eDate As Date
    Dim iDate As Integer
            
    sDate = "02/04/2018"
    eDate = "04/06/2018"
    
    iDate = DateDiff("m", sDate, eDate)
        
    MsgBox "The number of months between " & sDate & " and " & eDate & " : " & iDate, vbInformation, "VBA DateDiff Function"
    
End Sub

Output: Here is the screen shot of the second example output.
VBA DateDiff Function

Example 3: Compute the number of years between a start date and end date

Let us see another example of the VBA DateDiff function. This below example computes the number of years between a start date and end date.

'Compute the number of years between a start date and end date
Sub VBA_DateDiff_Function_Ex3()

    'Variable declaration
    Dim sDate As Date
    Dim eDate As Date
    Dim iDate As Integer
            
    sDate = "02/04/2018"
    eDate = "04/06/2025"
    
    iDate = DateDiff("yyyy", sDate, eDate)
        
    MsgBox "The number of years between " & sDate & " and " & eDate & " : " & iDate, vbInformation, "VBA DateDiff Function"
    
End Sub

Output: Here is the screen shot of the third example output.
VBA DateDiff Function

Example 4: Compute the number of weeks between a start date and end date

One more example of the VBA DateDiff function. This below example computes the number of weeks between a start date and end date

'Compute the number of weeks between a start date and end date
Sub VBA_DateDiff_Function_Ex4()

    'Variable declaration
    Dim sDate As Date
    Dim eDate As Date
    Dim iDate As Integer
            
    sDate = "02/04/2018"
    eDate = "04/06/2018"
    
    iDate = DateDiff("w", sDate, eDate)
        
    MsgBox "The number of weeks between " & sDate & " and " & eDate & " : " & iDate, vbInformation, "VBA DateDiff Function"
    
End Sub

Output: Here is the screen shot of the fourth example output.
VBA DateDiff Function

Example 5: Compute the number of hours between a start time and end time

One more example of the VBA DateDiff function. This below example computes the number of hours between a start time and end time.

'Compute the number of hours between a start time and end time
Sub VBA_DateDiff_Function_Ex5()

    'Variable declaration
    Dim sTime As Date
    Dim eTime As Date
    Dim iTime As Integer
            
    sTime = "02:04:10"
    eTime = "08:06:35"
    
    iTime = DateDiff("h", sTime, eTime)
        
    MsgBox "The number of hours between " & sTime & " and " & eTime & " : " & iTime, vbInformation, "VBA DateDiff Function"
    
End Sub

Output: Here is the screen shot of the fifth example output.
VBA DateDiff Function

Instructions to Run VBA Macro Code or Procedure:

You can refer the following link for the step by step instructions.

Instructions to run VBA Macro Code

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

I am trying to create a formula or VBA function which calculates the number of months between two dates, according to this rule: if the start date is the 15th of the month or before, or the end date is after the 15th of the month, then that month counts.

For example:

Start Date   End Date   Output
----------   ---------  --------
1/5/2014     2/16/2014  2 months
1/17/2014    2/16/2014  1 month
1/16/2014    2/5/2014   0 months

I have already tried =DATEDIF(A2, B2, "M") + IF( DATEDIF(A2, B2, "MD")>=15, 1, 0) but this only adds a month if the distance between the days in 2 dates is over 15. For example if the start date is 5/14/13-8/16/13 it will say that there are 3 months in between these dates. However, the actual distance between these 2 dates should be 4 months according to the conditions that I specified above.

Ho do I fix this formula?

In this Article

  • DateDiff Description
  • Simple DateDiff Examples
  • DateDiff Syntax
  • Examples of Excel VBA DateDiff Function
    • Referencing Dates
    • Using Different Units of Interval

DateDiff Description

Returns the difference between two date values, based on the interval specified.

Simple DateDiff Examples

Here is a simple DateDiff example:

Sub DateDiff_Year()
    MsgBox DateDiff("yyyy", #1/1/2019#, #8/1/2021#)
End Sub

This code will return 2. This is difference on year (indicated by “yyyy”) between 2 days. (2021 – 2019 = 2)

In the example above, changing the positions of date1 and date2.

Sub DateDiff_Year()
    MsgBox DateDiff("yyyy", #8/1/2021#, #1/1/2019#)
End Sub

This code will return -2.

DateDiff Syntax

In the VBA Editor, you can type  “DateDiff(” to see the syntax for the DateDiff Function:

The DateDiff function contains 5 arguments:

Interval: Time unit (Days, Months, Years, etc.). Enter as string. (ex. “m” for Month)

Setting Description
yyyy Year
q Quarter
m Month
y Day of Year
d Day
w Weekday
ww Week
h Hour
n Minute
s Second

Date1, Date2: Two dates you want to use in the calculation.

FirstDayOfWeek: A constant that specifies the first day of the week. This is optional. If not specified, Sunday is assumed.

Constant Value Description
vbUseSystem 0 Use the NLS API setting.
vbSunday 1 Sunday (default)
vbMonday 2 Monday
vbTuesday 3 Tuesday
vbWednesday 4 Wednesday
vbThursday 5 Thursday
vbFriday 6 Friday
vbSaturday 7 Saturday

FirstWeekOfYear: A constant that specifies the first week of the year. This is optional. If not specified, the first week is assumed to be the week in which January 1 occurs.

Constant Value Description
vbUseSystem 0 Use the NLS API setting.
vbFirstJan1 1 Start with week in which January 1 occurs (default).
vbFirstFourDays 2 Start with the first week that has at least four days in the new year.
vbFirstFullWeek 3 Start with first full week of the year.

Examples of Excel VBA DateDiff Function

Referencing Dates

To start, we will demonstrate different ways to reference dates using the VBA DateDiff Function.

Each of these DateDiff functions produce the same result:

Sub DateDiff_ReferenceDates()

    MsgBox DateDiff("m", #4/1/2019#, #8/1/2021#)

    MsgBox DateDiff("m", DateSerial(2019, 4, 1), DateSerial(2021, 8, 1))

    MsgBox DateDiff("m", DateValue("April 1, 2019"), DateValue("August 1, 2021"))

End Sub

Or you can reference cells containing dates:

Sub DateDiff_ReferenceDates_Cell()

    MsgBox DateDiff("m", Range("C2").Value, Range("C3").Value)
    
End Sub

Or create and reference date variables:

Sub DateDiff_Variable()

    Dim dt1 As Date, dt2 As Date
    dt1 = #4/1/2019#
    dt2 = #8/1/2021#

    MsgBox DateDiff("m", dt1, dt2)

End Sub

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

Using Different Units of Interval

Quarters

Sub DateDiff_Quarter()
    MsgBox "the number of quarters: " & DateDiff("q", #1/1/2019#, #1/1/2021#)
End Sub

Months

Sub DateDiff_Month()
    MsgBox "the number of months: " & DateDiff("m", #1/1/2019#, #1/1/2021#)
End Sub

Days

Sub DateDiff_Day()
    MsgBox "the number of days: " & DateDiff("d", #1/1/2019#, #1/1/2021#)
End Sub

Weeks

Sub DateDiff_Week()
    MsgBox "the number of weeks: " & DateDiff("w", #1/1/2019#, #1/1/2021#)
End Sub

Hours

Sub DateDiff_Hour()
    Dim dt1 As Date
    Dim dt2 As Date
    Dim nDiff As Long
    
    dt1 = #8/14/2019 9:30:00 AM#
    dt2 = #8/14/2019 1:00:00 PM#
    
    nDiff = DateDiff("h", dt1, dt2)

    MsgBox "hours: " & nDiff
End Sub

Minutes

Sub DateDiff_Minute()
    MsgBox "mins: " & DateDiff("n", #8/14/2019 9:30:00 AM#, #8/14/2019 9:35:00 AM#)
End Sub

Seconds

Sub DateDiff_Second()
    MsgBox "secs: " & DateDiff("s", #8/14/2019 9:30:10 AM#, #8/14/2019 9:30:22 AM#)
End Sub

DateDiff function in VBA is an inbuilt function in VBA, categorized under the Date and Time function in VBA. We can use this function to get the difference between two dates. This function takes three arguments. The first argument is what part of the difference we want, which can be years, days or months, or seconds and two dates, and the result is an integer.

Table of contents
  • DATEDIFF Function in VBA
    • What is the DATEDIFF Function in Excel VBA?
    • Examples of DATEDIFF Function in Excel VBA
      • Example #1 – To Find Differences in Days
      • Example #2 – To Find Difference in Months
      • Example #3 – To Find Difference in Years
      • Assignment as a Practice
    • Recommended Articles

VBA DateDiff 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 DateDiff Function (wallstreetmojo.com)

The DateDiff function in VBA calculates the difference between two dates in days, months, quarters, and years.

In Excel, finding the difference between two dates has many ways. You do not need a special formula to calculate the difference between two dates.

For example, look at the below image.

datediff Example 1

If we want to calculate the difference between these two dates, we can subtract date 1 from date 2.

datediff Example 1-1

It has given us the difference between two dates in several days. However, it is a problem with this generic formula. If we need the difference in months, years, quarters, etc., it cannot give.

This article will show you how to use this DateDiff function in VBA.

What is the DATEDIFF Function in Excel VBA?

The Datediff in VBA stands for “Date Difference between two dates.”

This function can give us the number of the time interval between two dates. When we want to find the difference between two dates, we can find it in days, weeks, months, quarters, etc.

To understand the function, look at the below syntax of the function.

DateDiff

Interval: This is nothing but in what way you want to calculate the date difference. The same list is below, whether in days, months, weeks, quarters, etc.

Datediff 1

Date 1: What is the first date you want to find the difference?

Date 2: What is the second date you want to find the difference from Date 1?

Here, the formula is Date 2 – Date 1.

[First Day of Week]: What is the first day of the week? We can agree with the following arguments.

[First Week Of the Year]: What is the year’s first week? 

datediff 2

[First Week Of the Year]: What is the year’s first week? We can enter the following arguments.

datediff 3

Examples of DATEDIFF Function in Excel VBA

The following are examples of Excel VBA DateDiff.

You can download this VBA DateDiff Function Template here – VBA DateDiff Function Template

Example #1 – To Find Differences in Days

Assume you have two dates, “15-01-2018” and “15-01-2019”. Let’s find all kinds of differences between these two dates.

Step 1: Create a macro name first.

Code:

Sub DateDiff_Example1()

End Sub

VBA DateDiff Example 1
Step 2: Define Two Variables as Date.

Code:

Sub DateDiff_Example1()

   Dim Date1 As Date
   Dim Date2 As Date

End Sub

VBA DateDiff Example 1-1

Step 3: Now, for the Date1 variable, assign “15-01-2018,” and for the Date2 variable, assign “15-01-2019.”

Code:

Sub DateDiff_Example1()

   Dim Date1 As Date
   Dim Date2 As Date

   Date1 = "15-01-2018"
   Date2 = "15-01-2019"

End Sub

VBA DateDiff Example 1-2

Step 4: Now, define one more variable, “As Long,” to store results.

Code:

Sub DateDiff_Example1()

   Dim Date1 As Date
   Dim Date2 As Date
   
   Dim Result As Long

   Date1 = "15-01-2018"
   Date2 = "15-01-2019"
End Sub

VBA DateDiff Example 1-3

Step 5: Now, assign the value for this variable through the DateDiff function in VBA.

Code:

Sub DateDiff_Example1()

   Dim Date1 As Date
   Dim Date2 As Date

   Dim Result As Long

   Date1 = "15-01-2018"
   Date2 = "15-01-2019"

Result =DateDiff(

End Sub

VBA DateDiff Example 1-4

Step 6: The first argument is what kind of difference we need between these dates. We need to find the number of days, so supply the argument as “D.”

Code:

Sub DateDiff_Example1()
    
    Dim Date1 As Date
    Dim Date2 As Date

    Dim Result As Long

   Date1 = "15-01-2018"
   Date2 = "15-01-2019"

   Result =DateDiff("D",

End Sub

VBA DateDiff Example 1-5

Step 7: What is the first date to find the difference? Our first date is “15-01-2018,” which we have already assigned to the variable “Date1”. So, supply the variable name here.

Code:

Sub DateDiff_Example1()

    Dim Date1 As Date
    Dim Date2 As Date

    Dim Result As Long

    Date1 = "15-01-2018"
    Date2 = "15-01-2019"

    Result =DateDiff("D",Date1,

End Sub

VBA DateDiff Example 1-6

Step 8: What is the second date to find the difference? The second date is “15-01-2019,” which holds the value through the variable “Date2.”.

Code:

Sub DateDiff_Example1()

    Dim Date1 As Date
    Dim Date2 As Date

    Dim Result As Long

    Date1 = "15-01-2018"
    Date2 = "15-01-2019"

    Result = DateDiff("D", Date1, Date2)

End Sub

VBA DateDiff Example 1-7

Step 9: Ignore the last two parameters. Now, assign the variable “Result” value through the VBA message boxVBA MsgBox function is an output function which displays the generalized message provided by the developer. This statement has no arguments and the personalized messages in this function are written under the double quotes while for the values the variable reference is provided.read more.

Code:

Sub DateDiff_Example1()

    Dim Date1 As Date
    Dim Date2 As Date
    Dim Result As Long

    Date1 = "15-01-2018"
    Date2 = "15-01-2019"

    Result = DateDiff("D", Date1, Date2)

    MsgBox Result

End Sub

VBA DateDiff Example 1-8

Now, run the code using the F5 key or manually. We will get the difference between these two dates in numbers.

Example 1-9

So, from “15-01-2018” to “15-01-2019,” the exact difference is one year, so we got 365 days.

Like this, we can find the difference between two dates in time intervals.

Example #2 – To Find Difference in Months

Code:

Sub DateDiff_Example2()

   Dim Date1 As Date
   Dim Date2 As Date
   
   Dim Result As Long

   Date1 = "15-01-2018"
   Date2 = "15-01-2019"

   Result = DateDiff("M", Date1, Date2)

   MsgBox Result
End Sub

Example 2

Run this code using the F5 key. You can run it manually to show the result as given below.

Example 2-1

Example #3 – To Find Difference in Years

Code:

Sub DateDiff_Example3()

   Dim Date1 As Date
   Dim Date2 As Date

   Dim Result As Long

  Date1 = "15-01-2018"
  Date2 = "15-01-2019"

  Result = DateDiff("YYYY", Date1, Date2)

  MsgBox Result

End Sub

Example 3

Run this code using the F5 key or manually to see the result.

Example 3-1

Assignment as a Practice

We hope you have understood the function of VBA DateDiff. Take a look at the below homework for you. Find the difference between the below dates in “Months.”

Example 4

If you have not found the way, below is the readymade code.

Code:

Sub Assignment()

    Dim k As Long

    For k = 2 To 8
        Cells(k, 3).Value = DateDiff("M", Cells(k, 1), Cells(k, 2))
    Next k

End Sub

Example 4-1

You can run this code manually or press the F5 key to see the result.

Example 4-2

Recommended Articles

This article is a guide to VBA DateDiff Function. Here we learn how to use DateDiff Function to find differences in days, months, and years in Excel VBA, practical examples, and a downloadable template. Below you can find some useful Excel VBA articles: –

  • DATE Function in Excel
  • Date Excel Format
  • Date Function in VBA
  • DateAdd in VBA
  • VBA COUNTA

Функция DateAdd
DateAdd(Interval, Number, Date)
Функция DateAdd используется для прибавления или вычитания указанного интервала времени. Тип данных Date работает только с датами диапазона от 100 г.н.э. до 9999 г.н.э. Поэтому, если DateAdd выходит за пределы этого диапазона, то генерируется ошибка стадии выполнения Invalid procedure call or argument. Функция DateAdd не возвращает неправильных дат. Следующее выражение добавляет один месяц к 31 января:

DateAdd(«m», 1, «31-Jan-95»)

В данном случае будет возвращена дата 28-фев-95, а не 31-фев-95. Если в качестве аргумента date указать 31-янв-96, то возвращается дата 29-фев-96, поскольку 1996 год является високосным

Возвращаемое значение
Возвращает значение типа Variant(Date), содержащее дату, к которой добавлен указанный интервал

Параметры
Функция содержит именованные аргументы
Interval
Обязательный аргумент типа String, указывающего тип добавляемого временного интервала: yyyy Год
q Квартал
m Месяц
y День года
d День месяца
w День недели
ww Неделя
h Часы
n Минуты
s Секунды
Interval не чуствителен к регистру букв. Литерал должен быть заключен в кавычки. Для добавления дней можно использовать любое значение интервала дня:»y», «w» или «d»
Number
Обязательный аргумент — числовое выражение, указывающее число добавляемых временных интервалов. Может быть положительным(для получения более поздних дат) и отрицательным(для получения более ранних дат). Если Number дробное число, то дробная часть отбрасывается(не округляется) системой
Date
Обязательный аргумент типа Variant(Date) или литерал даты(буквенное обозначение даты, представляющий дату, к которой прибавляется указанный временной интервал
Пример
‘ Вычисляем дату на 15 дней более позднюю, чем текущая
Dim Today
Dim NewDate As Date
Today=Date ‘ узнаем текущую системную дату
NewDate=DateAdd(«y»,15,Today)
‘ Преобразуем в строку и выводим в заголовке формы
Form1.Caption = CStr(NewDate)

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