Excel vba добавить дату

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

Функция Date

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

Синтаксис

Пример

Sub PrimerDate()

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

End Sub

Функция DateAdd

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

Синтаксис

DateAdd(interval, number, date)

Параметры

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

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

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

Пример

Sub PrimerDateAdd()

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

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

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

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

End Sub

Функция DateDiff

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

Синтаксис

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

Параметры

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

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

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

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

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

Пример

Sub PrimerDateDiff()

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

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

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

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

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

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

End Sub

Функция DatePart

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

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

Синтаксис

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

Параметры

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

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

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

Пример

Sub PrimerDatePart()

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

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

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

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

End Sub

Функция DateSerial

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

Синтаксис

DateSerial(year, month, day)

Параметры

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

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

Пример

Sub PrimerDateSerial()

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

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

End Sub

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

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

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

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

Функция DateValue

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

Синтаксис

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

Пример

Sub PrimerDateValue()

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

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

End Sub

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

Функция Day

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

Синтаксис

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

Пример

Sub PrimerDay()

    MsgBox Day(Now)

End Sub

Функция IsDate

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

Синтаксис

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

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

Пример

Sub PrimerIsDate()

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

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

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

End Sub

Функция Hour

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

Синтаксис

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

Пример

Sub PrimerHour()

    MsgBox Hour(Now)

    MsgBox Hour(«22:36:54»)

End Sub

Функция Minute

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

Синтаксис

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

Пример

Sub PrimerMinute()

    MsgBox Minute(Now)

    MsgBox Minute(«22:36:54»)

End Sub

Функция Month

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

Синтаксис

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

Пример

Sub PrimerMonth()

    MsgBox Month(Now)

End Sub

Функция MonthName

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

Синтаксис

MonthName(month, [abbreviate])

Параметры

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

Пример

Sub PrimerMonthName()

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

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

End Sub

Функция Now

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

Синтаксис

Пример

Sub PrimerNow()

    MsgBox Now

    MsgBox Day(Now)

    MsgBox Hour(Now)

End Sub

Функция Second

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

Синтаксис

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

Пример

Sub PrimerSecond()

    MsgBox Second(Now)

    MsgBox Second(«22:30:14»)

End Sub

Функция Time

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

Синтаксис

Пример

Sub PrimerTime()

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

End Sub

Функция TimeSerial

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

Синтаксис

TimeSerial(hour, minute, second)

Параметры

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

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

Пример

Sub PrimerTime()

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

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

End Sub

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

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

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

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

Функция TimeValue

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

Синтаксис

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

Пример

Sub PrimerTimeValue()

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

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

End Sub

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

Функция Weekday

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

Синтаксис

Weekday(date, [firstdayofweek])

Параметры

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

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

Пример

Sub PrimerWeekday()

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

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

End Sub

Функция WeekdayName

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

Синтаксис

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

Параметры

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

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

Пример

Sub PrimerWeekdayName()

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

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

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

End Sub

Функция Year

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

Синтаксис

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

Пример

Sub PrimerYear()

    MsgBox Year(Now)

End Sub

Приложение 1

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

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

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

Приложение 2

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

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

Приложение 3

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

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

In this Article

  • DateAdd Description
  • Simple DateAdd Examples
  • DateAdd Syntax
  • Examples of Excel VBA DateAdd Function
    • Referencing Dates
    • Add or Subtract Dates
    • Adding Different Units of Time
    • Add to Today
    • Adding and Subtracting Time
  • Formatting Dates

DateAdd Description

The VBA DateAdd Function allows you to add (or subtract) days, months, years, hours, quarters, etc. to Dates or Times.

Simple DateAdd Examples

Here is a simple DateAdd example:

Sub DateAdd_Day()
    MsgBox DateAdd("d", 20, #4/1/2021#)
End Sub

This code will add 20 days (indicated by “d”) to the date 4/1/2021:

vba dateadd function

Instead, we can change the Interval argument from “d” to “m” to add 20 months to the date 4/1/2021:

Sub DateAdd_Month()
    MsgBox DateAdd("m", 20, #4/1/2021#)
End Sub

vba dateadd months

Instead of displaying the date in a message box, we can assign it to a variable:

Sub DateAdd_Day2()
    Dim dt as Date    
    dt = DateAdd("d", 20, #4/1/2021#)

    MsgBox dt
End Sub

DateAdd Syntax

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

vba dateadd syntax

The DateAdd function contains 3 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

Number: Numeric value representing the number of time units to add. (ex. 20 to add 20 units)

Date: Initial Date. See next section.

Examples of Excel VBA DateAdd Function

Referencing Dates

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

Each of these DateAdd functions produce the same result:

Sub DateAdd_ReferenceDates()

    MsgBox DateAdd("m", 2, #4/1/2021#)

    MsgBox DateAdd("m", 2, DateSerial(2021, 4, 1))

    MsgBox DateAdd("m", 2, DateValue("April 1, 2021"))

End Sub

Or you can reference a cell containing a date:

dateadd function cellvalue

Sub DateAdd_ReferenceDates_Cell()

    MsgBox DateAdd("m", 2, Range("C2").Value)

End Sub

Or create and reference a date variable:

Sub DateAdd_Variable()

    Dim dt As Date
    dt = #4/1/2021#

    MsgBox DateAdd("m", 2, dt)

End Sub

Add or Subtract Dates

We have already shown you how to add to a date:

Sub DateAdd_Day2()
    Dim dt as Date    
    dt = DateAdd("d", 20, #4/1/2021#)

    MsgBox dt
End Sub

You can subtract from dates by using a negative number (ex. -20 instead of 20):

Sub DateAdd_Day()
    Dim dt as Date    
    dt = DateAdd("d", -20, #4/1/2021#)

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

Adding Different Units of Time

Years

Sub DateAdd_Years()
    MsgBox DateAdd("yyyy", 4, #4/1/2021#)
End Sub

Quarter

Sub DateAdd_Quarters()
    MsgBox DateAdd("q", 2, #4/1/2021#)
End Sub

Month

Sub DateAdd_Months()
    MsgBox DateAdd("m", 2, #4/1/2021#)
End Sub

Day of Year

Sub DateAdd_DaysofYear()
    MsgBox DateAdd("y", 2, #4/1/2021#)
End Sub

Day

Sub DateAdd_Days3()
    MsgBox DateAdd("d", 2, #4/1/2021#)
End Sub

Weekday

Sub DateAdd_Weekdays()
    MsgBox DateAdd("w", 2, #4/1/2021#)
End Sub

Week

Sub DateAdd_Weeks()
    MsgBox DateAdd("ww", 2, #4/1/2021#)
End Sub

Add to Today

These examples will add units of time to today using the Date Function.

Sub DateAdd_Year_Test()
    Dim dtToday As Date
    Dim dtLater As Date
    
    dtToday = Date
    dtLater = DateAdd("yyyy", 1, dtToday)
    
    MsgBox "A year later is " & dtLater
End Sub
Sub DateAdd_Quarter_Test()
    MsgBox "2 quarters later is " & DateAdd("q", 2, Date)
End Sub

Adding and Subtracting Time

The DateAdd function also works with Times.  Here are a few examples of adding (or subtracting) time to a time:

Hour

This example will add 2 hours to a time:

Sub DateAdd_Hour()
    MsgBox DateAdd("h", 2, #4/1/2021 6:00:00#)
End Sub

Minute

This example will subtract 120 minutes from the Current Time:

Sub DateAdd_Minute_Subtract()
    MsgBox DateAdd("n", -120, Now)
End Sub

Second

Sub DateAdd_Second()
    MsgBox DateAdd("s", 2, #4/1/2021 6:00:00#)
End Sub

VBA Programming | Code Generator does work for you!

Formatting Dates

When dates (or times) are displayed in Excel, UserForms, or Messageboxes, you should indicate how the dates should be displayed by using the Format Function.  We’ve included a few examples below:

Sub FormattingDatesTimes()

    'Returns Current Date and Time
    dt = Now()
    
    'ex. 07/02/2021
    Range("B2") = Format(dt, "mm/dd/yyyy")
    
    'ex. July 2, 2021
    Range("B3") = Format(dt, "mmmm d, yyyy")
    
    'ex. July 2, 2021 09:10
    Range("B4") = Format(dt, "mm/dd/yyyy hh:mm")
    
    'ex. 7.2.21 9:10 AM
    Range("B5") = Format(dt, "m.d.yy h:mm AM/PM")

End Sub

vba dates

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

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

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

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

title keywords f1_keywords ms.prod ms.assetid ms.date ms.localizationpriority

DateAdd function (Visual Basic for Applications)

vblr6.chm1013094

vblr6.chm1013094

office

68d4e339-67b2-37e7-214d-318edd683b23

12/12/2018

high

Returns a Variant (Date) containing a date to which a specified time interval has been added.

Syntax

DateAdd(interval, number, date)

The DateAdd function syntax has these named arguments:

Part Description
interval Required. String expression that is the interval of time you want to add.
number Required. Numeric expression that is the number of intervals you want to add. It can be positive (to get dates in the future) or negative (to get dates in the past).
date Required. Variant (Date) or literal representing the date to which the interval is added.

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

Remarks

Use the DateAdd function to add or subtract a specified time interval from a date. For example, you can use DateAdd to calculate a date 30 days from today or a time 45 minutes from now.

To add days to date, you can use Day of Year («y»), Day («d»), or Weekday («w»).

[!NOTE]
When you use the «w» interval (which includes all the days of the week, Sunday through Saturday) to add days to a date, the DateAdd function adds the total number of days that you specified to the date, instead of adding just the number of workdays (Monday through Friday) to the date, as you might expect.

The DateAdd function won’t return an invalid date. The following example adds one month to January 31:

DateAdd("m", 1, "31-Jan-95")

In this case, DateAdd returns 28-Feb-95, not 31-Feb-95. If date is 31-Jan-96, it returns 29-Feb-96 because 1996 is a leap year.

If the calculated date would precede the year 100 (that is, you subtract more years than are in date), an error occurs.

If number isn’t a Long value, it is rounded to the nearest whole number before being evaluated.

[!NOTE]
The format of the return value for DateAdd is determined by Control Panel settings, not by the format that is passed in the date argument.

[!NOTE]
For date, if the Calendar property setting is Gregorian, the supplied date must be Gregorian. If the calendar is Hijri, the supplied date must be Hijri. If month values are names, the name must be consistent with the current Calendar property setting. To minimize the possibility of month names conflicting with the current Calendar property setting, enter numeric month values (Short Date format).

Example

This example takes a date and, using the DateAdd function, displays a corresponding date a specified number of months in the future.

Dim FirstDate As Date    ' Declare variables.
Dim IntervalType As String
Dim Number As Integer
Dim Msg As String
IntervalType = "m"    ' "m" specifies months as interval.
FirstDate = InputBox("Enter a date")
Number = InputBox("Enter number of months to add")
Msg = "New date: " & DateAdd(IntervalType, Number, FirstDate)
MsgBox Msg

See also

  • Functions (Visual Basic for Applications)

[!includeSupport and feedback]

The DateAdd function is categorized under the Date and Time function in VBA. This function has an output value as a date. In addition, it takes input as a date format and adds it to the current date to return a new date. The syntax for this function takes three arguments: interval, number, and date.

Using the DateAdd function, we can add and subtract days, months, and years from the given date. The date in Excel is part and parcel of our daily work. We cannot work in Excel without date, time, and other important stuff. The common process is adding one date to another and subtracting one date from another. In the regular worksheet, we do arithmetic operations and get the result. In VBA, we have the function called DateAdd, which will do the job.

Table of contents
  • Excel VBA DateAdd Function
    • Syntax
    • How to Use Dateadd Function in VBA?
      • Example #1 – Add Date
      • Example #2 – Add Months
      • Example #3 – Add Years
      • Example #4 – Add Quarter
      • Example #5 – Add Weekday
      • Example #6 – Add Week
      • Example #7 – Add Hour
      • Example #8 – Subtract Date
    • Recommended Articles

VBA DateAdd Function

Syntax

VBA DateAdd Formula

Interval: Interval is nothing but what kind of value you want to add or subtract. For example, whether you want to add or subtract a month, whether you want to add or subtract days, whether you want to add or subtract a year, whether you want to add or subtract a quarter, etc.

Below is a list of codes and descriptions.

list of codes its descriptions

  • Number: The number of months, days, or weeks (as provided in the interval) we want to add or subtract to the date.
  • Date: The actual date value we are doing the arithmetic operation.

For example, if you have the date “14-Mar-2019” and you want to add two days to the date, use the below code:

DateAdd (“d,” 2, “14-03-2019”)

The result of the above code is: 16-03-2019

How to Use Dateadd Function in VBA?

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

Example #1 – Add Date

To start the proceedings, let’s apply the simple DateAdd function. Assume you are working with the date “14-03-2019”.

Step 1: Start the subprocedure by creating a macro name.

Step 2: Define the variable as Date.

Code:

Sub DateAdd_Example1()

Dim Month As Date

End Sub

Step 3: For this variable, assign a value.

Code:

Sub DateAdd_Example1()
  Dim NewDate As Date

  NewDate =

End Sub

Step 4: Start the DateAdd formula.

Code:

Sub DateAdd_Example1()
  Dim NewDate As Date

  NewDate = DateAdd(

End Sub

Step 5: What is the operation we want to do? We want a day to the date. So the interval is “d.”

Code:

Sub DateAdd_Example1()
    Dim NewDate As Date

   NewDate = DateAdd("d",

End Sub

Step 6: How many days do we need to add? We have to add 5 days.

Code:

Sub DateAdd_Example1()
   Dim NewDate As Date

   NewDate = DateAdd("d", 5,

End Sub

Step 7: Our date is “14-03-2019.

Code:

Sub DateAdd_Example1()
   Dim NewDate As Date

   NewDate = DateAdd("d", 5, "14-03-2019")

End Sub

Step 8: Show the result of the variable in 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 DateAdd_Example1()
  Dim NewDate As Date

  NewDate = DateAdd("d", 5, "14-03-2019")
  MsgBox NewDate

End Sub

If we run this code, we should get the date as 19-03-2019.

VBA DateAdd Example 1

The system’s date format is “mm-dd-yyyy,” so the result shows as per the system date settings.

However, we can modify this by applying the VBA FORMATThe format function in VBA is used to format the given values into the format that is desired. It can be used to format dates, numbers, and trigonometrical values, among other things.read more function.

Code:

Sub DateAdd_Example1()
  Dim NewDate As Date

  NewDate = DateAdd("d", 5, "14-03-2019")
  MsgBox Format(NewDate, "dd-mmm-yyyy")

End Sub

Now, the result should be like this: “19-Mar-2019.”

VBA DateAdd Example 1-1

Example #2 – Add Months

To add months, below is the code.

Code:

Sub DateAdd_Example2()
  'To add months
  Dim NewDate As Date

  NewDate = DateAdd("m", 5, "14-03-2019")
  MsgBox Format(NewDate, "dd-mmm-yyyy")

End Sub

The result will be:

VBA DateAdd Example 2

Example #3 – Add Years

To add years using DateAdd, use the below code.

Code:

Sub DateAdd_Example2()
  'To add year
  Dim NewDate As Date

  NewDate = DateAdd("yyyy", 5, "14-03-2019")
  MsgBox Format(NewDate, "dd-mmm-yyyy")

End Sub

The Result will be:

VBA DateAdd Example 2

Example #4 – Add Quarter

To add quarter, below is the code.

Code:

Sub DateAdd_Example2()
  'To add quarter
  Dim NewDate As Date

  NewDate = DateAdd("Q", 5, "14-03-2019")
  MsgBox Format(NewDate, "dd-mmm-yyyy")

End Sub

The Result will be:

VBA DateAdd Example 2-2

Example #5 – Add Weekday

To add weekdays, below is the code.

Code:

Sub DateAdd_Example2()
  'To add weekdays
  Dim NewDate As Date

  NewDate = DateAdd("W", 5, "14-03-2019")
  MsgBox Format(NewDate, "dd-mmm-yyyy")

End Sub

The Result will be:

Add weekday result Example 2-3

Example #6 – Add Week

To add a week, below is the code.

Code:

Sub DateAdd_Example2()
  'To add Week
  Dim NewDate As Date

  NewDate = DateAdd("WW", 5, "14-03-2019")
  MsgBox Format(NewDate, "dd-mmm-yyyy")

End Sub

The Result will be:

Add week result Example 2-4

Example #7 – Add Hour

To add the hour, below is the code.

Code:

Sub DateAdd_Example2()
  'To add hour
  Dim NewDate As Date

  NewDate = DateAdd("h", 5, "14-03-2019")
  MsgBox Format(NewDate, "dd-mmm-yyyy hh:mm:ss")

End Sub

The Result will be

Add hour result Example 2-5

Example #8 – Subtract Date

To add, we have supplied positive numbers. To subtract, we need to supply negative numbers that are all.

To subtract 3 months from the supplied date, below is the code.

Code:

Sub DateAdd_Example3()
  'To add hour
  Dim NewDate As Date

  NewDate = DateAdd("m", -3, "14-03-2019")
  MsgBox Format(NewDate, "dd-mmm-yyyy")

End Sub

The result of this code is:

subtract result Example 2-6

We deduct 3 months from the date 14th March 2019. So, it will return to the previous year.

Recommended Articles

This article is a guide to the VBA DateAdd Function. Here, we learn how to use the VBA DateAdd function to add and subtract days, months, and years from the given date, along with practical examples and a downloadable Excel template. Below you can find some useful Excel VBA articles: –

  • VBA Case Statement Examples
  • Weekday in VBA
  • VBA Select Case
  • DateSerial in VBA

VBA DateAdd function in Excel is categorized as a Date & Time function. This is a built-in Excel VBA Function. This function returns a date after which a certain time or date interval has been added.

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 DateAdd Function in any number of times in any number of procedures or functions. Let us learn what is the syntax and parameters of the DateAdd function, where we can use this DateAdd Function and real-time examples in Excel VBA.

Table of Contents:

  • Objective
  • Syntax of VBA DateAdd Function
  • Parameters or Arguments
  • Where we can apply or use VBA DateAdd Function?
  • Example 1: Add 4 days to the date
  • Example 2: Add 3 months to the date
  • Example 3: Add 2 years to the date
  • Example 4: Add 1 week to the date
  • Example 5: Add 3 hours to the time
  • Instructions to Run VBA Macro Code
  • Other Useful Resources

The syntax of the DateAdd Function in VBA is

DateAdd(Interval, Number, Date)

The DateAdd function returns a string value.

Parameters or Arguments:

The DateAdd function has three arguments in Excel VBA.
where
Interval:The Interval is a required argument. It takes one of the following 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

Number:The Number is a required argument. It represents the number of intervals that you want to add. It can be either positive or negative value. If it is negative get past dates, otherwise for positive value get future dates.
Date:The Date is a required argument. It represents date. It specifies which the interval is added.

Where we can apply or use VBA DateAdd Function?

We can use this DateAdd 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: Add 4 days to the date

Here is a simple example of the VBA DateAdd function. This below example adds 4 days to the date.

'Add 4 days to the date
Sub VBA_DateAdd_Function_Ex1()

    'Variable declaration
    Dim lDate As Date
    Dim oDate As Date
            
    lDate = "02/04/2018"
    oDate = DateAdd("d", 4, lDate)
        
    MsgBox "New date after adding 4 days : " & oDate, vbInformation, "VBA DateAdd Function"
    
End Sub

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

Example 2: Add 3 months to the date

Let us see one more example of the VBA DateAdd function. This below example adds 3 months to the date.

'Add 3 months to the date
Sub VBA_DateAdd_Function_Ex2()

    'Variable declaration
    Dim lDate As Date
    Dim oDate As Date
            
    lDate = "02/04/2018"
    oDate = DateAdd("m", 3, lDate)
        
    MsgBox "New date after adding 3 months : " & oDate, vbInformation, "VBA DateAdd Function"
    
End Sub

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

Example 3: Add 2 years to the date

Let us see another example of the VBA Date-add function. This below example adds 2 years to the date.

'Add 2 years to the date
Sub VBA_DateAdd_Function_Ex3()

    'Variable declaration
    Dim lDate As Date
    Dim oDate As Date
            
    lDate = "02/04/2018"
    oDate = DateAdd("yyyy", 2, lDate)
        
    MsgBox "New date after adding 2 years : " & oDate, vbInformation, "VBA DateAdd Function"
    
End Sub

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

Example 4: Add 1 week to the date

One more example of the VBA Date-add function. This below example adds 1 week to the date.

'Add 1 week to the date
Sub VBA_DateAdd_Function_Ex4()

    'Variable declaration
    Dim lDate As Date
    Dim oDate As Date
            
    lDate = "02/04/2018"
    oDate = DateAdd("ww", 1, lDate)
        
    MsgBox "New date after adding 1 week : " & oDate, vbInformation, "VBA DateAdd Function"
    
End Sub

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

Example 5: Add 3 hours to the time

One more example of the VBA DateAdd function. This below example adds 3 hours to the time.

'Add 3 hours to the time
Sub VBA_DateAdd_Function_Ex5()

    'Variable declaration
    Dim lTime As Date
    Dim oTime As Date
            
    lTime = "02:04:18"
    oTime = DateAdd("h", 3, lTime)
        
    MsgBox "New time after adding 3 hours : " & oTime, vbInformation, "VBA DateAdd Function"
    
End Sub

Output: Here is the screen shot of the fifth example output.
VBA DateAdd 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

VBA DateAdd

Excel VBA DateAdd

VBA DateAdd is a function which performs addition or subtraction of time/date intervals. This will return date by adding or subtracting a specified time interval. It is quite difficult to deal with date and time when you do some calculations on it. But in our daily work, it is an essential type of data that we may use. Comparison, addition, subtraction between different dates are some familiar operations that we do.

Formula For DateAdd function in Excel VBA

The formula for VBA DateAdd function is very simple in format.

Syntax of DateAdd

Let’s see what are the parameters used in the Excel VBA DateAdd function.

  • Interval: This can be a time/date interval that you want to add or subtract. This represents what kind of value you wish to add or subtract. This can be a component of date or time like days, month, etc. The scope of intervals is given below.

Interval

  • Number: Is the number of intervals you want to add. Use a positive number to add the interval with the given date and negative value to subtract the interval from the date.
  • Date: The date to which you want to add/subtract the interval. Operations will be performed on this date and return date as output.

Examples of Excel VBA DateAdd Function

Below are the different examples of DateAdd Function in Excel VBA:

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

Example #1 – Add Date

Let’s see how to add a particular number with the given date using VBA DateAdd Function.

  • We need to find the date after adding ’10’ days with the date ‘25/10/2015’
  • Start sub procedure with a name. Here we created a sub procedure named ‘adddate’.

Code:

Sub adddate()

End Sub

VBA DateAdd Example 1-1

  • Create a variable as date datatype, variable name is currentdate.

Code:

Sub adddate()

Dim currentdate As Date

End Sub

VBA DateAdd Example 1-2

  • We are going to store the result in this variable currentdate.
  • We want to add ‘10’ days with ‘25/10/2015’. So the number of days want to add is 10. And the interval is ‘d’ and the number is 10.
  • So let’s apply the VBA DateAdd function as below.

Code:

Sub adddate()

Dim currentdate As Date
currentdate = DateAdd("d", 10, "25/10/2015")

End Sub

VBA DateAdd Example 1-3

  • After applying the formula to the variable let’s use a message box to print the result.

Code:

Sub adddate()

Dim currentdate As Date
currentdate = DateAdd("d", 10, "25/10/2015")
MsgBox Format(currentdate, "dd-mm-yyyy")

End Sub

VBA DateAdd Example 1-4

  • Run the code by pressing F5. The result will be shown as

Result of Example 1-5

You can see the result as shown above.

Example #2 – Add Months

  • To add months with the given date the interval needs to change as “m”.
  • Add ‘2’ with the date “15/2/2017”. The code can be written as below.

Code:

Sub addmonth()

Dim currentdate As Date
currentdate = DateAdd("m", 2, "15/2/2017")
MsgBox Format(currentdate, "dd-mm-yyyy")

End Sub

VBA DateAdd Example 2-1

  • The output date will be changed as below.

Result of Example 2-2

Example #3 – Add Year

To add years with the given date the below code can be used.

  • The interval should be” yyyy”
  • Add 4 years with’20/2/2018’

Code:

Sub addyear()

Dim currentdate As Date
currentdate = DateAdd("yyyy", 4, "20/2/2018")
MsgBox Format(currentdate, "dd-mm-yyyy")

End Sub

VBA DateAdd Example 3-1

  • The result will be as below. The variable currentdate will return ‘20/2/2022’

Result of Example 3-2

Example #4 – Add Quarter

  • While adding quarter, three months will be added to the date since the quarter if 12 months is 3.
  • The interval should be mention as “Q”, the number given in the formula specifies how many quarters should be added. For example, DateAdd(“Q”,2, ”22/5/2019”) number of quarters is 2 so 6 months will be added.
  • To add 2 quarters with ‘22/5/2018’ below code can be used.

Code:

Sub addquarter()

Dim currentdate As Date
currentdate = DateAdd("Q", 2, "22/5/2019")
MsgBox Format(currentdate, "dd-mm-yyyy")

End Sub

VBA DateAdd Example 4-1

  • The result will be as below.

Result of Example 4-2

Example #5 – Add Seconds

  • You can add time along with date displayed. To get this mention the interval as “s” which indicates seconds.
  • To display five seconds with date ‘28/3/2019’ can use the below formula.

Code:

Sub addseconds()

Dim currentdate As Date
currentdate = DateAdd("s", 5, "28/3/2019")
MsgBox Format(currentdate, "dd-mm-yyyy hh:mm:ss")

End Sub

VBA DateAdd Example 5-1

  • While showing the output with date seconds will be displayed.

Result of Example 5-2

Example #6 – Add Weeks

  • To add a number of weeks with the given date, use the interval as “WW”
  • Code to find the date after the given number of weeks from’27/03/2016’

Code:

Sub addweek()

Dim currentdate As Date
currentdate = DateAdd("WW", 2, "27/3/2019")
MsgBox Format(currentdate, "dd-mm-yyyy")

End Sub

VBA DateAdd Example 6-1

  • The output will be the date after 2 weeks.

Result of Example 6-2

Example #7 – Add Hours

  • To get a particular time with a date this is used.
  • In interval mention the “h” and also change the format of the output.
  • The code to get the hours printed with a date is.

Code:

Sub addhour()

Dim currentdate As Date
currentdate = DateAdd("h", 12, "27/3/2019")
MsgBox Format(currentdate, "dd-mm-yyyy hh:mm:ss")

End Sub

VBA DateAdd Example 7-1

  • The result will be shown with time in hh:mm:ss.

Result of Example 7-2

Example #8 – How to Subtract Weeks using VBA DateAdd Function?

Similar to addition, subtraction can also perform using VBA DateAdd function. The numbers specified as positive integers along with the formula. To perform subtraction, use these numbers as negative integers. For example, change the formula as below.

DateAdd (interval, - number, date)

By using the above method will try to find the day subtracting three weeks from ‘28/3/2019’

  • Create a subprocedure as subdate.

Code:

Sub subdate()

End Sub

VBA DateAdd Example 8-1

  • Define a variable to store the result. Currentdate is a variable as date type to assign the final result.

Code:

Sub subdate()

Dim currentdate As Date

End Sub

VBA DateAdd Example 8-2

  • To subtract three weeks from ‘28/3/2019’ will apply the formula. DateAdd(“ww”, -3, “28/3/2019”)

Code:

Sub subdate()

Dim currentdate As Date
currentdate = DateAdd("ww", -3, "28/3/2019")

End Sub

VBA DateAdd Example 8-3

‘-3’ indicates the subtraction “ww” is the interval since we want to operate on weeks.

  • The formula is applied and the result is stored in currentdate.

Code:

Sub subdate()

Dim currentdate As Date
currentdate = DateAdd("ww", -3, "28/3/2019")
MsgBox Format(currentdate, "dd-mm-yyyy")

End Sub

VBA DateAdd Example 8-4

  • The result after subtracting three weeks from the given date is displayed below.

Result of Example 8-5

Things to Remember

  • The interval and date mentioned in the formula will be given within a double quotation.
  • If you use weekdays interval” w” it will work similarly to the interval day “d” since the weekday calculates 1=Sunday, 2=Monday, etc. in So it will count the holidays even you use weekdays.
  • The out will be displayed according to the date format settings on your system. Use format along with a message box to print the result in the format you want.
  • Within the VBA DateAdd function use the number as negative to perform subtraction among dates.

Recommended Articles

This is a guide to Excel VBA DateAdd Function. Here we discuss the examples of VBA DateAdd function to add & subtract days, months & years from the given date along with practical examples and downloadable excel template. You can also go through our other suggested articles –

  1. VBA Date
  2. VBA Date Format
  3. VBA Time
  4. VBA DatePart

Понравилась статья? Поделить с друзьями:
  • Excel vba для чего option explicit
  • Excel vba заголовок умной таблице
  • Excel vba для libreoffice
  • Excel vba зависимые выпадающие списки
  • Excel vba заблокировать ячейку в excel