Функции для работы с датой и временем в 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 | Первая полная неделя года. |
Visual Basic for Applications (VBA) is integrated into the programs that come with the Microsoft Office suite, like Microsoft Word and Microsoft Excel. VBA lets you write macros (short, simple programs), which can be used to automate a task you perform repetitively. For example, in Excel you can write a macro that lets you copy the data found in a range of cells from one column and paste it in another column.
You can see how useful this is – especially if you use Excel for office work!Using Visual Basic for Applications requires a certain familiarity with the Visual Basic language. Visual Basic was developed by Microsoft to make it easy for developers to make Windows-friendly applications. If you’re unfamiliar with Visual Basic for Applications, you should consider signing up for an introductory VBA course with us. We’ll go over everything you need to know (from the basics to the advanced stuff) – you’ll be writing your own macros in no time. Before we proceed, you may want to go through this quick primer on VBA, to brush up the basics.
The DateDiff Function Syntax
In this tutorial, we’re going to give you a detailed, easy to understand overview of the DateDiff function in VBA. We’ll also teach you how to write your own macros from the basics. Even if you’re unfamiliar with the process, you should be able to create a functioning macro if you follow the steps outlined in this tutorial to the letter.
The DateDiff function in VBA can be used to find out the time interval between two distinct specified time periods. The syntax for the DateDiff function is:
DateDiff (interval, date1, date2, [firstdayofweek], [firstweekofyear])
You always have to specify the interval, date1 and date2 parameters. You don’t need to specify the firstdayofweek and firstweekofyear parameters. You can change the interval parameter to day, weekday, week, hour, second or year (among other values). The date1 and date2 will be starting date and the ending date of your two periods- and the interval you specify will be how you receive your result. For example, if you wanted to find out the difference between two dates in number of days, you will have to use the “days” interval. If you wanted to find out the difference between two dates in number weeks, you will have to use the “week” time interval. If you don’t specify the firstdayofweek parameter, the first day of the week will be set as Sunday. If you don’t specify the firstweekofyear parameter, the first week of the year will be set as the week which contains Jan 1.
Creating a Command Button
Before we show you the code to write the DateDiff function, you should insert a command button in your Excel spreadsheet. What is a command button and why do we need one? A command button, when clicked, runs the code it was linked to. You can use command buttons to start the execution of a macro and to get results. An example of a command button would be the “=” button found on the calculator built into Windows. In our case, we will link the command button to the DateDiff function.
First, you should enable the developer tab in Excel. This tab is disabled by default. The developer lets you create macros and add features and designs to your spreadsheet. To enable the tab, right click on the ribbon at the top and choose the “Customize the Ribbon…” option in the drop down menu. Here, you should select the “Developer Tab” option and click on ok, like in the screenshot below. You can also look this up in our 24-Hour VBA trainer course.
A new tab called Developer will now be available next to the View tab at the top. The Developer tab has the command button we’re after. Find the Insert Option and choose the “Command Button” under the Active X controls sub-menu. The Design Mode button at the top will become highlighted and your pointer will turn into a black cross. Click on any cell in the spreadsheet to spawn a command button, like in the screenshot given below:
You can drag and drop the command button anywhere in the spreadsheet. The Caption that appears on the command button is “CommandButton 1” by default. You can change the name of the command button by right clicking on it and choosing properties. A large list of properties will pop up to the left. We recommend you don’t change anything here (especially if you’re new to VBA), except the Caption label. Renaming the Caption label will change the visiblename of your command button to something else. For example, in our image we’ve change the visible caption of the Command Button to “Find Date”:
Now, we need to write code for our DateDiff function and link it to this command button. This way, when we click on “Find Date”, the DateDiff function will return a value. Right click on the command button and choose the “View Code” option. This will open up the Microsoft Visual Basic for Applications screen. This is where we write the code. It should look something like this:
We will write the code for the DateDiff function between the Private Sub CommandButton1_Click() and End Sub statements. The CommandButton1_Click() line of code tells VBA to execute code found after it when a user clicks on the command button. You can learn more about how to create your own macros and command buttons in this VBA course.
Using DateDiff Function to Find Difference between Two Dates in Days
Now, finally, we can write the code for the DateDiff function. First, let’s create a DateDiff function that lets us find out the difference between two time periods in number of days. The syntax for the DateDiff function, as we mentioned above, is:
DateDiff (interval, date1, date2, [firstdayofweek], [firstweekofyear])
First, we need to initialize three different variables to hold the values of the result (in number of days) and the two time periods: date1 and date2. If you’ve studied other languages before (like C or Java), you know why we need to declare these variables. If you’re unfamiliar with programming, you can also just sign up for a basic C programming course with us.
The code to declare variables would be as follows:
Dim dateone As Date, datetwo as Date, days As Integer
Here, we have declared dateone and datetwo as “Date” variables. They will hold data in a date format (“ Month Day, Year”). Days will hold data as an “Integer” (number).
Next, we need to assign values to thedateone and datetwo variables. These will be our two time periods:
dateone = DateValue(“Mar 10, 2014”) datetwo = DateValue(“Mar 15, 2014”)
Then, we write the DateDiff function. We use the “days” variable for this purpose:
days = DateDiff (“d”, dateone, datetwo)
Here, the “d” tells Visual Basic to use the “day” time interval.
Finally, we need to display the result. For this, we use a message box. Just type a single line of code at the end:
MsgBox days
The complete program is as follows :
Private Sub CommandButton1_Click() Dim dateone As Date, datetwo as Date, days As Integer dateone = DateValue(“Mar 10, 2014”) datetwo = DateValue(“Mar 15, 2014”) days = DateDiff (“d”, dateone, datetwo) MsgBox days End Sub
You can copy paste the entire code, but we recommend you type it on your own to get a feel for VB. Once you’re done typing, alt tab to your Excel Spreadsheet. The Design Mode will be active- click on the Design Mode button (in the developer tab) to deactivate it. Finally, click on the command button. A message box with the difference in dates should pop up. You can change the values of the dateone and datetwo variables to get different results. You can also try out some of the examples in this VBA course for Excel.
Using DateDiff Function to Find Difference between Two Dates in Weeks
You can use the DateDiff function to find difference between two specified dates in number of weeks, instead of number of days. The code is similar- you just have to replace the “d” (interval) parameter with “ww”. Just modify the program we wrote earlier, like this:
Private Sub CommandButton1_Click() Dim dateone As Date, datetwo As Date, days As Integer dateone = DateValue("Mar 10, 2014") datetwo = DateValue("Mar 15, 2014") days = DateDiff("ww", dateone, datetwo) MsgBox days End Sub
Now try clicking on the command button (remember to disable design mode). You will get “0” as the result. Why did that happen?
In this case, the difference between the two dates was 0 in number of weeks. If you changed the value of dateone or datetwo be a month or two, you will get a different result. Try experimenting for yourself and see. You can also change the time interval to second (s), minute (n), hour (h), day of year (y) or month (y). For a list, select the DateDiff function in VBA with your mouse (highlight it) and press F1. You can try specifying the firstdayofweek and firstweekofyear parameters as well.
The DateDiff function is one of the simplest and most useful functions in VBA. Feel free to experiment with it. Once you’re ready to step it up a notch, go stretch yourself with our Advanced VBA course.
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!
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 »
28 Апрель 2011 326760 просмотров
- 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() — возможность создать значение даты, задавая месяц, год и день числовыми значениями:
- DateValue()— делает то же, что и DateSerial(). Отличия — в формате принимаемых значений. Эта функция в качестве аргумента принимает дату в текстовом формате и преобразует её в формат даты:
MsgBox DateValue("07.06.12")
Аналогичным образом (для времени) работают TimeSerial() и TimeValue()
- Day(), Year(), Month(), Weekday(), Hour(), Minute(), Second() — специализированные заменители функции DatePart(), которые возвращают нужную часть даты/времени (которую именно — видно из названия).
- MonthName() — возвращает имя месяца словами по его номеру. Возвращаемое значение зависит от региональных настроек. Если они русские, то вернется русское название месяца.
- Timer() — возвращает количество секунд, прошедших с полуночи.
MsgBox DateSerial(2012, 6, 7)
Статья помогла? Сделай твит, поделись ссылкой с друзьями!
title | keywords | f1_keywords | ms.prod | ms.assetid | ms.date | ms.localizationpriority |
---|---|---|---|---|---|---|
DateDiff function (Visual Basic for Applications) |
vblr6.chm1012950 |
vblr6.chm1012950 |
office |
15c9df5f-1403-b6a5-71b9-611e9820d804 |
12/12/2018 |
high |
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. |
Remarks
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.
[!NOTE]
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.
Dim TheDate As Date ' Declare variables. Dim Msg TheDate = InputBox("Enter a date") Msg = "Days from today: " & DateDiff("d", Now, TheDate) MsgBox Msg
See also
- Functions (Visual Basic for Applications)
[!includeSupport and feedback]