Vba excel разницу во времени

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

Функция Date

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

Синтаксис

Пример

Sub PrimerDate()

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

End Sub

Функция DateAdd

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

Синтаксис

DateAdd(interval, number, date)

Параметры

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

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

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

Пример

Sub PrimerDateAdd()

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

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

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

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

End Sub

Функция DateDiff

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

Синтаксис

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

Параметры

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

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

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

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

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

Пример

Sub PrimerDateDiff()

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

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

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

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

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

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

End Sub

Функция DatePart

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

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

Синтаксис

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

Параметры

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

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

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

Пример

Sub PrimerDatePart()

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

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

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

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

End Sub

Функция DateSerial

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

Синтаксис

DateSerial(year, month, day)

Параметры

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

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

Пример

Sub PrimerDateSerial()

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

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

End Sub

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

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

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

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

Функция DateValue

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

Синтаксис

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

Пример

Sub PrimerDateValue()

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

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

End Sub

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

Функция Day

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

Синтаксис

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

Пример

Sub PrimerDay()

    MsgBox Day(Now)

End Sub

Функция IsDate

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

Синтаксис

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

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

Пример

Sub PrimerIsDate()

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

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

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

End Sub

Функция Hour

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

Синтаксис

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

Пример

Sub PrimerHour()

    MsgBox Hour(Now)

    MsgBox Hour(«22:36:54»)

End Sub

Функция Minute

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

Синтаксис

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

Пример

Sub PrimerMinute()

    MsgBox Minute(Now)

    MsgBox Minute(«22:36:54»)

End Sub

Функция Month

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

Синтаксис

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

Пример

Sub PrimerMonth()

    MsgBox Month(Now)

End Sub

Функция MonthName

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

Синтаксис

MonthName(month, [abbreviate])

Параметры

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

Пример

Sub PrimerMonthName()

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

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

End Sub

Функция Now

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

Синтаксис

Пример

Sub PrimerNow()

    MsgBox Now

    MsgBox Day(Now)

    MsgBox Hour(Now)

End Sub

Функция Second

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

Синтаксис

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

Пример

Sub PrimerSecond()

    MsgBox Second(Now)

    MsgBox Second(«22:30:14»)

End Sub

Функция Time

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

Синтаксис

Пример

Sub PrimerTime()

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

End Sub

Функция TimeSerial

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

Синтаксис

TimeSerial(hour, minute, second)

Параметры

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

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

Пример

Sub PrimerTime()

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

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

End Sub

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

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

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

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

Функция TimeValue

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

Синтаксис

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

Пример

Sub PrimerTimeValue()

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

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

End Sub

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

Функция Weekday

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

Синтаксис

Weekday(date, [firstdayofweek])

Параметры

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

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

Пример

Sub PrimerWeekday()

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

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

End Sub

Функция WeekdayName

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

Синтаксис

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

Параметры

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

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

Пример

Sub PrimerWeekdayName()

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

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

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

End Sub

Функция Year

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

Синтаксис

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

Пример

Sub PrimerYear()

    MsgBox Year(Now)

End Sub

Приложение 1

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

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

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

Приложение 2

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

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

Приложение 3

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

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

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

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

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

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

I need to calculate the difference of two different times.

For example,

time1 = 6:45 AM
time2 = 7:30 AM

Then, i need to convert it to hours (integer)

So in Basic Math, this is:

timediff = time2 - time1
timediff = 0:45

timediff(in hrs) = 0 + (45/60)
timediff(in hrs) = 0.75

I need to do this in VBA. Can someone help me?
Thanks a lot!

Alex K.'s user avatar

Alex K.

170k30 gold badges263 silver badges286 bronze badges

asked Feb 12, 2015 at 10:39

xtina1231's user avatar

DateDiff() computes this (n indicates minutes):

?DateDiff("n", "6:45", "7:30") / 60
 0.75 

answered Feb 12, 2015 at 12:00

Alex K.'s user avatar

Alex K.Alex K.

170k30 gold badges263 silver badges286 bronze badges

This was the first hit I got on a google-search for VBA timediff: http://www.ozgrid.com/forum/showthread.php?t=45698&p=231656#post231656

I believe it should do what you want with minimal modification.

The UDF defined in that post is:

Function TimeDiff(StartTime As Date, StopTime As Date) 
    TimeDiff = abs(StopTime-StartTime) * 86400 
End Function 

answered Feb 12, 2015 at 11:15

eirikdaude's user avatar

eirikdaudeeirikdaude

3,0916 gold badges25 silver badges49 bronze badges

This worked for me. After lots of fits and starts, it seems simple.
The result value dtDuration (actually a double) is also used to update an Hours (double) field in a table.

Dim dtDuration As Double
dtDuration = DateDiff("s", CDate(strStarTime), CDate(strCompTime))

Me.txtCalcHours.SetFocus
Me.txtCalcHours.Text = dtDuration / 3600

answered Sep 17, 2015 at 15:49

John H Funk's user avatar

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

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

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

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