Vba excel time and date of

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

Excel VBA Date & Time Functions; Year, Month, Week & Day Functions

——————————————————

Contents:

VBA DateSerial Function

VBA DateValue Function

VBA TimeSerial Function

VBA TimeValue Function

VBA IsDate Function

VBA CDate Function

VBA DateAdd Function

VBA DateDiff Function

VBA DatePart Function

VBA Date Function

VBA Now Function

VBA MonthName Function

VBA Day Function

VBA Month Function

VBA Year Function

VBA Hour Function

VBA Minute Function

VBA Second Function

VBA WeekDay Function

VBA WeekdayName Function

Using Find Method to Search for a Date

—————————————————— 

Working with dates and times in Excel VBA can be tricky. There are a number of ways to represent dates in Excel. It is important to ensure that the Date will actually remain the date value which you actually mean to refer or use in your code. Date format is dependent on the regional and date-specific settings of your system / computer, and lack of understanding in using date functions can result in varying formats or incorrect interpretations. Excel VBA Date Functions are used in your code to work with and manipulate dates & times; to validate date values; convert serial numbers or strings to date formats; extract date parts like day, week, month & year; add and subtract date and time intervals; use the current date, the current time, or the day of the week; and so on.

We have explained in detail various aspects of using Dates & Times in Excel VBA, and also the Format Function to use Predefined Named Formats & to create User-Defined Formats, in our separate section of «Excel VBA Dates & Time, Format Function, User Defined Date, Number & String Formats». In this section we deal with some important Excel VBA Date Functions.

VBA DateSerial Function

The VBA DateSerial Function returns (Date value) a date for a specified year, month and day. Syntax: DateSerial(year, month, day). All 3 arguments are necessary to specify. Year argument is an Integer, can be a number within the range 100 and 9999, or can be a numeric expression. Month argument is an Integer, can be a number within a valid range of 1 and 12, or can be a numeric expression. Day argument is an Integer, can be a number within a valid range of 1 and 31, or can be a numeric expression. A numeric expression can also be used to specify relative dates for each argument, say, to represent a number of years or months or days before or after a specific date.

When values supplied for an argument exceeds its acceptable range, the increment will be to the next applicable unit, for example, supplying 14 as the value for the month argument will increment to the second month (February) of the next year. The Function will return an error in the case of any argument value being outside the range -32,768 to 32,767 or in case the final date (after evaluating the 3 arguments) falls outside the valid date range.

The supplied values for the year, month & day arguments are assumed to be Gregorian or Hijri, as per the Calendar property setting if Gregorian or Hijri. The Function returns the date part in the time period units of the current Calendar, so that if the date part to be returned is the year, the year value is a Gregorian year where the current Calendar is Gregorian.

It is advisable to use a four-digit year to ensure returning the correct Date by using this Function. Earlier versions of Windows interpret two-digit years based on certain defaults: Specifying two-digit years for the year argument are read as per user-defined desktop settings in Windows 98 or Windows 2000 systems, wherein the default settings read values from 0 to 29 as the years 2000 to 2029 and values from 30 to 99 as the years 1930 to1999 and for all other years the four-digit year is used.

Sub DateSerialFunc_1()

Dim MyDate As Variant

MyDate = DateSerial(2012, 5, 8)

‘returns «5/8/2012»

MsgBox MyDate

‘returns «May 08, 2012»

MsgBox Format(MyDate, «mmmm dd, yyyy»)

‘specify relative dates for an argument, using a numeric expression

‘returns «5/17/2010» (2 years before and 9 days later than the specified date of «5/8/2012»)

MsgBox DateSerial(2012 — 2, 5, 8 + 9)

End Sub

Sub DateSerialFunc_2()

Dim MyDate As Variant

‘Date increments to the second month (February) of the next year

MyDate = DateSerial(2012, 14, 8)

‘returns «2/8/2013»

MsgBox MyDate

‘returns «February 08, 2013»

MsgBox Format(MyDate, «mmmm dd, yyyy»)

‘—————-

‘Date will increment to 5th of next month (May is a 31 day month: 35-31 = 4)

MyDate = DateSerial(2012, 5, 35)

‘returns «6/4/2013»

MsgBox MyDate

‘returns «June 04, 2013»

MsgBox Format(MyDate, «mmmm dd, yyyy»)

‘—————-

‘Date will increment to 5th of next month (June is a 30 day month: 35-30 = 5)

MyDate = DateSerial(2012, 6, 35)

‘returns «7/5/2013»

MsgBox MyDate

‘returns «July 05, 2013»

MsgBox Format(MyDate, «mmmm dd, yyyy»)

‘—————-

‘gives a run time error — value for any argument is outside the range -32,768 to 32,767:

MyDate = DateSerial(2012, 32768, 5)

‘—————-

‘gives a run time error — final date (per the 3 arguments) falls outside the valid date range:

MyDate = DateSerial(9999, 16, 5)

End Sub

VBA DateValue Function

Use the DateValue function to convert a string to a Date (Date value). Syntax: DateValue(date). The date argument can be a string expression representing a date, or any expression representing a date or time or both. The expression should represent a date within the range January 1, 100 to December 31, 9999.

Refer below example which illustrates in detail on using the DateValue Function.

Sub DateValueFunc()

‘VBA DateValue Function

Dim vDate As Variant

‘you can assign a date literal to a Variant or Date variable

vDate = #7/5/2012#

‘returns «7/5/2012»

MsgBox DateValue(vDate)

‘—————

‘DateValue Function returns only the Date part (and not Time part) of an expression

Dim MyDate As Date

‘returns «8/13/2013 11.06.25 AM»

MyDate = Format(Now, «mmmm dd, yyyy hh:mm:ss«)

MsgBox MyDate

‘returns «8/13/2013»

MyDate = Format(DateValue(Now), «mmmm dd, yyyy hh:mm:ss«)

MsgBox MyDate

‘returns «August 13, 2013 00:00:00»

MsgBox Format(DateValue(«08/13/2013 11.06.25 AM»), «mmmm dd, yyyy hh:mm:ss»)

‘—————

‘for a string that includes only numbers, and which is separated by valid date separators, your System’s Short Date format determines the sequence for month, day & year for the DateValue Function.

‘for a system Short Date format of «m/d/yyyy» — returns «4/11/2013» meaning «April 11, 2013»

MsgBox DateValue(«4/11/2013»)

‘returns «April 11, 2013»

MsgBox Format(DateValue(«4/11/2013»), «mmmm dd, yyyy»)

‘for a system Short Date format of «m/d/yyyy» — returns «11/4/2013» meaning «November 04, 2013»

MsgBox DateValue(«11/4/2013»)

‘returns «November 04, 2013»

MsgBox Format(DateValue(«11/4/2013»), «mmmm dd, yyyy»)

‘—————

‘Month names, in both long or abbreviated forms, are also recognized by the DateValue function.

‘returns «11/4/2013»

MsgBox DateValue(«Nov 4, 13»)

‘—————

‘if the year is omitted, the current year is considered as per the system date in your computer.

‘returns «4/25/2013», if the current year is 2013

MsgBox DateValue(«4/25»)

‘—————

‘DateValue Function returns an error for an invalid format

vDate = #4:01:26 PM#

‘returns 12:00:00 AM» (DateValue Function returns only the Date part, and not Time part)

MsgBox DateValue(vDate)

vDate = «36:01:26«

‘returns an error because of invalid time format

MsgBox DateValue(vDate)

End Sub

VBA TimeSerial Function

The VBA TimeSerial Function returns a Time (Date value) for a specified hour, minute & second. Syntax: TimeSerial(hour, minute, second). All 3 arguments are necessary to specify.The hour argument is an Integer, a number within a valid range of 0 and 23, and can be any numeric expression. The minute argument is an Integer, a number within a valid range of 0 and 59, and can be any numeric expression. The second argument is an Integer, a number within a valid range of 0 and 59, and can be a numeric expression. A numeric expression can also be used to specify relative times for each argument, say, to represent a number of hours or minutes or seconds before or after a specific time.

When values supplied for an argument exceeds its acceptable range, the increment will be to the next applicable unit, for example, supplying 70 as the value for the minute argument will increment to the ten minutes of the next hour. The Function will return an error in the case of any argument value being outside the range -32,768 to 32,767 or in case the final date (after evaluating the 3 arguments) falls outside the valid date range.

Refer below example which illustrates in detail on using the TimeSerial Function.

Sub TimeSerialFunc()

Dim vTime As Variant

‘—————-

vTime = TimeSerial(14, 5, 18)

‘returns «2:05:18 PM» — as per your system’s Long Time Format setting — «h:mm:ss AM/PM«

‘changing your system’s Long Time Format setting to 24-hr format of «h:mm:ss» will return the time as «14:05:18»

MsgBox vTime

‘user-defined Time format with VBA Format Function — returns «02:5:18 P»

MsgBox Format(vTime, «hh:n:ss A/P»)

‘—————-

‘value of 85 supplied for minutes argument exceeds its acceptable range of 0 to 59, hence 85 will be evaluated as 1 hr 25 minutes thus incrementing time to the next hour

vTime = TimeSerial(14, 85, 18)

‘returns «3:25:18 PM»

MsgBox vTime

‘—————-

‘using a numeric expression to specify relative times for each argument:

Dim vHr As Variant, vMin As Variant, vSec As Variant

‘returns «7:08:24 PM»

MsgBox TimeSerial(19, 8, 24)

vHr = 3

vMin = 21

vSec = 4

‘returns «4:29:20 PM»

MsgBox TimeSerial(19 — vHr, 8 + vMin, 24 — vSec)

‘—————-

‘gives a run time error — value for any argument is outside the range -32,768 to 32,767:

MsgBox TimeSerial(19, 32768, 5)

End Sub 

VBA TimeValue Function

Use the VBA TimeValue function to convert a string to a time (Date value). Syntax: TimeValue(time) . The time argument can be a string expression representing a time, or any expression representing a time. The expression should represent a time within the range 0:00:00 (12:00:00 A.M.) to 23:59:59 (11:59:59 P.M.), inclusive.

Refer below example which illustrates in detail on using the TimeValue Function.

Sub TimeValueFunc()
‘VBA TimeValue Function

Dim vTime As Variant

‘—————

‘you can assign a time literal to a Variant or Date variable

vTime = #5:06:25 PM#

‘returns «5:06:25 PM»

MsgBox TimeValue(vTime)

‘—————

‘time values using a 12-hour or 24-hour format can be entered

‘returns «5:06:25 AM»

MsgBox TimeValue(«05:06:25»)

‘returns «5:06:25 PM»

MsgBox TimeValue(«17:06:25»)

‘—————

‘TimeValue Function returns only the Time part (and not Date part) of an expression

Dim MyTime As Date

‘returns «8/13/2013 11.06.25 AM»

MyTime = Format(Now, «mmmm dd, yyyy hh:mm:ss«)

MsgBox MyTime

‘returns «11.06.25 AM»

MyTime = Format(TimeValue(Now), «mmmm dd, yyyy hh:mm:ss«)

MsgBox MyTime

‘—————

‘TimeValue Function returns an error for an invalid format

vTime = «36:01:26«

‘returns an error because of invalid time format

MsgBox TimeValue(vTime)

End Sub

Example: Extract Date Part and Time Format from a cell value — use DateValue & TimeValue Functions

Sub DateValueTimeValue()
‘Extract Date Part and Time Format from a cell value (cell A1 contains the value 41463.251).

Dim MyDateTime As Date, MyDate As Date, MyTime As Date

Dim strDate As String, strTime As String

‘——————-

‘OPTION 1:

‘It is necessary to convert the expression (cell value) to a String or Date to use the DateValue / TimeValue functions.

‘cell A1 contains the value 41463.251 — Format function converts to a string value.

strDate = Format(Range(«A1»), «mm/dd/yyyy«)

strTime = Format(Range(«A1»), «hh:mm:ss AMPM«)

‘convert string to a Date by using DateValue & TimeValue functions which extract Date & Time parts

MyDate = DateValue(strDate)

MyTime = TimeValue(strTime)

‘returns «7/8/2013»

MsgBox MyDate

‘returns «6:01:26 AM»

MsgBox MyTime

MyDateTime = MyDate + MyTime

‘returns «7/8/2013 6:01:26 AM»

MsgBox MyDateTime

‘——————-

‘OPTION 2:

‘cell A1 contains the value 41463.251

‘returns «7/8/2013 6:01:26 AM», in date format

MyDateTime = Range(«A1«).Value

MsgBox MyDateTime

‘returns «7/8/2013»

MyDate = DateValue(MyDateTime)

MsgBox MyDate

‘returns «6:01:26 AM»

MyTime = TimeValue(MyDateTime)

MsgBox MyTime

‘——————-

‘OPTION 3:

‘cell A1 contains the value 41463.251

‘returns «7/8/2013 6:01:26 AM», in date format

MyDateTime = Range(«A1«).Value

MsgBox MyDateTime

‘returns «7/8/2013»

MyDate = MyDateTime — TimeValue(MyDateTime)

MsgBox MyDate

‘returns «6:01:26 AM»

MyTime = MyDateTime — DateValue(MyDateTime)

MsgBox MyTime

End Sub

VBA IsDate Function

The VBA IsDate Function is used to check if an expression is a Date or the expression can be converted to a valid Date or Time — the function returns True in this case, else False is returned. Syntax: IsDate(expression). Valid date can range from January 1, 100 to December 31, 9999 in Microsoft Windows operating system (will vary for different systems).

Sub IsDateFunc()

Dim var As Variant

var = «12/18/2011«

‘returns True (valid date)

MsgBox IsDate(var)

var = «18/12/2011«

‘returns True (valid date)

MsgBox IsDate(var)

var = «18/15/2011«

‘returns False (invalid date)

MsgBox IsDate(var)

var = «24 Jan, 2001«

‘returns True (valid date)

MsgBox IsDate(var)

var = «June 31, 2001«

‘returns False (invalid date)

MsgBox IsDate(var)

var = «18.12.11«

‘returns True (valid Time)

MsgBox IsDate(var)

var = «18.12.2011«

‘returns False (invalid Time)

MsgBox IsDate(var)

var = 21345

‘returns False (invalid Date/Time)

MsgBox IsDate(var)

End Sub

VBA CDate Function

Use the VBA CDate function to convert a value to a date (Date value). Syntax: CDate(expression). Refer below examples which explain the CDate Function in detail.

Sub CDateFunc_1()

‘CDate sets date format based on your system’s locale setting

‘returns «3/12/2013»

MsgBox CDate(41345)

‘returns «6:01:26 AM»

MsgBox CDate(0.251)

End Su

Sub CDateFunc_2()

Dim strDate As String, strTime As String

Dim vDate As Variant, vTime As Variant

strDate = «September 24, 1984«

strTime = «17:42:36«

‘set vDate to a Date value.

vDate = CDate(strDate)

‘returns «September 24, 1984»

MsgBox strDate

‘returns «9/24/1984» (CDate sets date format based on your system’s locale setting)

MsgBox vDate

‘set vTime to Date value.

vTime = CDate(strTime)

‘returns «17:42:36»

MsgBox strTime

‘returns «5:42:36 PM»

MsgBox vTime

End Sub

Sub InputBoxDateFormat()

‘date format with InputBox

Dim strDate As String

strDate = InputBox(«Enter date«)

‘Use the IsDate function to determine if a value can be converted to a date and time.

If IsDate(strDate) Then

‘CDate function converts a value to a date. CDate recognizes date formats based on your system’s locale setting. Ensure that you provide the day, month, and year in the correct sequence or order per your locale setting, or the date might not be correctly interpreted. A long date format containing a string value specifying a weekday like ‘Tuesday’ will not be recognized.

strDate = Format(CDate(strDate), «dd/mm/yyyy«)

‘displays date in the format of day-month-year

MsgBox strDate

Else

MsgBox «Invalid date»

End If

End Sub

VBA DateAdd Function

Use the VBA DateAdd Function to add or subtract a specified time interval to a Date — it returns (Date value) a future or past Date after adding or subtracting the specified time interval. Syntax: DateAdd(interval, number, date). All 3 arguments are necessary to specify. Interval argument is a String value, specifying the time interval you wish to add or subtract. Number argument is a numeric specifying the number of time intervals — use a positive number for future dates and a negative to get past dates. Date argument specifies the Date (Variant) to which you want to add or subtract the time interval.

Settings for the interval argument: yyyy — Year; q — Quarter; m — Month; y — Day of Year; d — Day; w — Weekday; ww — Week; h — Hour; n — Minute; s — Second.

Note that the Date returned by the function is as per your system-defined date format, and not by the format used in date argument.

Sub DateAddFunc()

Dim vDate As Variant

Dim strInterval As String

‘——————————

‘use y — Day of Year, d — Day or w — Weekday to add days to a date.

vDate = #8/11/2013#

strInterval = «y«

‘returns «8/16/2013»

MsgBox DateAdd(strInterval, 5, vDate)

strInterval = «d«

‘returns «8/16/2013»

MsgBox DateAdd(strInterval, 5, vDate)

strInterval = «w«

‘returns «8/16/2013»

MsgBox DateAdd(strInterval, 5, vDate)

‘——————————

vDate = #1/25/2004#

‘returns «2/25/2004»

MsgBox DateAdd(«m», 1, vDate)

vDate = #1/31/2004#

‘returns «2/29/2004» (2004 is a leap year)

MsgBox DateAdd(«m», 1, vDate)

vDate = #1/31/2004#

‘returns «2/28/2004»

MsgBox DateAdd(«ww», 4, vDate)

vDate = #1/25/2004#

‘returns «7/25/2004» — rounds off the number argument to the nearest whole number, if not a Long value.

MsgBox DateAdd(«q», 2.2, vDate)

vDate = #1/25/2004#

‘returns «7/25/2004» — rounds off the number argument to the nearest whole number, if not a Long value.

MsgBox DateAdd(«q», 2.2, vDate)

‘Note that the Date returned by the function is as per your system-defined date format, and not by the format used in date argument.

‘returns «7/27/1994».

MsgBox DateAdd(«yyyy», -2, «July 27, 1996»)

‘returns «2:23:12 PM».

MsgBox DateAdd(«n», -5, «14:28:12»)

‘returns «1:23:12 PM».

MsgBox DateAdd(«n», -65, «14:28:12»)

‘the Function will return an error, if the calculated date is not within the valid date range.

‘returns an error because the year precedes 100:

MsgBox DateAdd(«yyyy», -1900, «No 27, 1996»)

End Sub

VBA DateDiff Function

Use the VBA DateDiff Function to return the number (Long) of time intervals between two dates. Syntax:  DateDiff(interval, date1, date2, firstdayofweek, firstweekofyear). The arguments of interval, date1 & date2 are necessary to specify, while it is optional to specify firstdayofweek & firstweekofyear arguments. The interval argument is a String value, specifying the time interval which is used to calculate the date1 & date2 difference. Date1 & date2 are the two dates whose difference is being calculated. The firstdayofweek argument is a constant, specifying the first day of the week — Default is Sunday. The firstweekofyear argument is a constant, specifying the first week of the year — Default is the week containing January 1.

Settings for the interval argument: yyyy — Year; q — Quarter; m — Month; y — Day of Year; d — Day; w — Weekday; ww — Week; h — Hour; n — Minute; s — Second.

Constants to be used for the argument firstdayofweek: vbUseSystem (value 0) — use NLS API setting; vbSunday (this is the default) (value 1) — Sunday; vbMonday (value 2) — Monday; vbTuesday (value 3) — Tuesday; vbWednesday (value 4) — Wednesday; vbThursday (value 5) — Thursday; vbFriday (value 6) — Friday; vbSaturday ( value 7) — Saturday.

Constants to be used for the argument firstweekofyear: vbUseSystem (value 0) — use NLS API setting; vbFirstJan1 (this is the default) (value 1) — start with week in which January 1 occurs; vbFirstFourDays (value 2) — start with the first week which has at least four days in the year; vbFirstFullWeek (value 3) — start with the first full week of the year which has all 7 days.

Where date1 is later than date2, a negative value is returned by the DateDiff function.

Refer below examples which explain the DateDiff Function in detail.

Sub DateDiffFunc_1()

‘CALCULATE NO. OF DAYS BETWEEN TWO DATES

Dim vDate1 As Variant, vDate2 As Variant

Dim strInterval As String

‘use y — Day of Year or d — Day, to calculate no. of days between two dates.

vDate1 = #2/25/2004#

vDate2 = #3/5/2004#

strInterval = «y«

‘calculate number of days between two dates: returns 9 (2004 is leap year)

MsgBox DateDiff(strInterval, vDate1, vDate2)

strInterval = «d«

‘calculate number of days between two dates: returns -9 (2004 is leap year)

‘Where first date is later than second date, a negative value is returned by the DateDiff function.

MsgBox DateDiff(strInterval, vDate2, vDate1)

End Sub

Sub DateDiffFunc_2()

‘CALCULATE NO. OF WEEKS BETWEEN TWO DATES

Dim vDate1 As Variant, vDate2 As Variant

Dim strInterval As String

‘vDate1 is a Tuesday

vDate1 = #3/5/2013#

‘vDate2 is a Sunday

vDate2 = #3/17/2013#

‘returns Tuesday

MsgBox Format(vDate1, «dddd»)

‘returns Sunday

MsgBox Format(vDate2, «dddd»)

strInterval = «w«

‘calculate number of weeks between two dates — returns 1

‘vDate1 is a Tuesday, and when using interval of «w» (Weekday) DateDiff will count number of Tuesdays till vDate2

MsgBox DateDiff(strInterval, vDate1, vDate2)

strInterval = «ww«

‘calculate number of weeks between two dates — returns 2

‘when using interval of «ww» (Week) DateDiff counts number of calendar weeks (ie. the number of Sundays) from vDate1 till vDate2

MsgBox DateDiff(strInterval, vDate1, vDate2)

strInterval = «ww«

‘calculate number of weeks between two dates — returns 1

‘when using interval of «ww» (Week) DateDiff counts number of calendar weeks (ie. the number of Sundays) from vDate1 till vDate2

‘the firstdayofweek argument can affect the calculation when using interval of «ww» ((Week)- the Sunday falling on March 10, 2013 will not be counted below.

MsgBox DateDiff(strInterval, vDate1, vDate2, vbMonday)

‘vDate1 is a Sunday

vDate1 = #3/10/2013#

‘vDate2 is a Sunday

vDate2 = #3/17/2013#

strInterval = «ww«

‘calculate number of weeks between two dates (both vDate1 & vDate2 are Sundays) — returns 1

‘using interval of «ww» (Week), DateDiff counts number of Sundays from vDate1 till vDate2 — it counts vDate2 if it falls on a Sunday but not vDate1 even if it falls on a Sunday.

MsgBox DateDiff(strInterval, vDate1, vDate2)

End Sub

Sub DateDiffFunc_3()

‘CALCULATE NO. OF MONTHS ELAPSED FROM A SPECIFIC DATE TILL TODAY

Dim vDate1 As Variant, vDate2 As Variant

Dim strInterval As String

vDate1 = #8/25/2012#

‘current date

vDate2 = Now

MsgBox «Months elapsed from » & Format(vDate1, «mmmm d, yyyy») & » till today are: » & DateDiff(«m», vDate1, vDate2)

End Sub

Sub DateDiffFunc_4()

‘CALCULATE NO. OF QUARTERS / YEARS BETWEEN TWO DATES

Dim vDate1 As Variant, vDate2 As Variant

Dim strInterval As String

vDate1 = #12/31/2012#

vDate2 = #1/1/2013#

strInterval = «q«

‘calculate number of quarters between two dates: returns 1, even though the difference between dates is of 1 day

MsgBox DateDiff(strInterval, vDate1, vDate2)

strInterval = «yyyy«

‘calculate number of years between two dates: returns 1, even though the difference between dates is of 1 day

MsgBox DateDiff(strInterval, vDate1, vDate2)

End Sub

Sub DateDiffFunc_5()

‘If both dates are entered as ‘date literal’, the year specified therein is used for calculation in the DateDiff function. But if the dates are enclosed in double quotation marks («) & the year is omitted, the dates are evaluated by inserting the current year in your code.

Dim vDate1 As Variant, vDate2 As Variant

Dim strInterval As String

vDate1 = #2/25/2004#

vDate2 = #3/5/2004#

strInterval = «d«

‘calculate number of days between two dates — returns 9 (2004 is leap year)

MsgBox DateDiff(strInterval, vDate1, vDate2)

‘dates are enclosed in double quotation marks («) & the year is omitted

vDate1 = «2/25«

vDate2 = «3/5«

strInterval = «d«

‘calculate number of days between two dates — returns 8 (dates are evaluated by inserting the current year, which is not a leap year)

MsgBox DateDiff(strInterval, vDate1, vDate2)

End Sub

VBA DatePart Function

Use the VBA DatePart Function to return (Integer) a specified part of a date. Syntax: DatePart(interval, date, firstdayofweek, firstweekofyear). The arguments of interval & date are necessary to specify, while it is optional to specify firstdayofweek & firstweekofyear arguments. The interval argument is a String value — it is the time interval you want to return from the date being evaluated. The date argument is the Date value which is evaluated and whose time interval is to be returned. The firstdayofweek argument is a constant, specifying the first day of the week — Default is Sunday. The firstweekofyear argument is a constant, specifying the first week of the year — Default is the week containing January 1.

Settings / Constants for the interval, firstdayofweek &  firstweekofyear arguments are the same as in the VBA DateDiff Function explained above.

Refer below example which explains the DatePart Function in detail.

Sub DatePartFunc()

‘VBA DatePart Function

Dim vDate As Variant

Dim strInterval As String

vDate = #2/25/2004#

strInterval = «y«

‘returns 56 — the Day of year

MsgBox DatePart(strInterval, vDate)

strInterval = «d«

‘returns 25 — the Day part of the date

MsgBox DatePart(strInterval, vDate)

‘returns 28 — the minute part of the Time

MsgBox DatePart(«n», «14:28:12»)

‘returns 14 — the hour part of the Time

MsgBox DatePart(«h», «2:28:12 PM»)

‘returns 3 — the Weekday in date (#3/5/2013# is Tuesday), Sunday being the first day of week

MsgBox DatePart(«w», #3/5/2013#)

‘the firstdayofweek argument can affect the calculation when using interval of «w» ((Weekday)

‘returns 2 — the Weekday in date (#3/5/2013# is Tuesday), Monday being the first day of week

MsgBox DatePart(«w», #3/5/2013#, vbMonday)

‘returns the Week in date, considering Sunday to be the first day of week

‘returns 2 — second week starts from «1/6/2013» which is a Sunday

MsgBox DatePart(«ww», #1/7/2013#)

‘the firstdayofweek argument can affect the calculation when using interval of «ww» ((Week)

‘returns the Week in date, considering Tuesday to be the first day of week

‘returns 1 — second week starts from «1/8/2013» which is a Tuesday

MsgBox DatePart(«ww», #1/7/2013#, vbTuesday)

‘If both dates are entered as ‘date literal’, the year specified therein is used for calculation in the DateDiff function. But if the dates are enclosed in double quotation marks («) & the year is omitted, the dates are evaluated by inserting

the current year in your code.

‘returns 61 — day of year is evaluated for the year 2004 which is leap year

MsgBox DatePart(«y», #3/1/2004#)

‘returns 60 — day of year is evaluated by inserting the current year, which is not a leap year

MsgBox DatePart(«y», «3/1»)

End Sub

VBA Date Function

The VBA Date function returns (Date value) the current system date. VBA Code: MsgBox Date — returns the current system date (ex. «8/11/2013»)

VBA Now Function

The VBA Now function returns (Date value) the current system date and time. VBA Code: MsgBox Now — returns the current system date & ime (ex. «8/11/2013 2:26:32 PM»)

VBA MonthName Function

Use the VBA MonthName Function to return (String) the month name from a given number. Syntax: MonthName(month, abbreviate). The month argument is necessary to specify, and it is a numeric representing a month, ex. January is 1, February is 2, and so on. The abbreviate argument is optional, it is a Boolean value wherein False (default) indicating that the month name should not be abbreviated. VBA Code: MsgBox MonthName(8, True) — returns «Aug».

VBA Day Function

Use the VBA Day Function to return (Integer) the day of the month from a given date — it returns a whole number between 1 and 31. Syntax: Day(date). The date argument can be a Variant, or a numeric or string expression, representing a valid date. VBA Code: MsgBox Day(«August 24, 2012») — returns «24».

VBA Month Function

Use the VBA Month Function to return (Integer) the month of the year from a given date — it returns a whole number between 1 and 12. Syntax: Month(date). The date argument can be a Variant, or a numeric or string expression, representing a valid date. VBA Code: MsgBox Month(«August 24, 2012») — returns «8».

VBA Year Function

Use the VBA Year Function to return (Integer) the year from a given date — it returns a whole number. Syntax: Year(date). The date argument can be a Variant, or a numeric or string expression, representing a valid date. VBA Code: MsgBox Year(«August 24, 2012») — returns «2012».

VBA Hour Function

Use the VBA Hour Function to return (Integer) the hour from a given time — it returns a whole number between 0 and 23. Syntax: Hour(time). The time argument can be a Variant, or a numeric or string expression, representing a valid time. VBA Code: MsgBox Hour(«2:04:36 PM») — returns «14».

VBA Minute Function

Use the VBA Minute Function to return (Integer) the minute of the hour from a given time — it returns a whole number between 0 and 59. Syntax: Minute(time). The time argument can be a Variant, or a numeric or string expression, representing a valid time. VBA Code: MsgBox Minute(«2:04:36 PM») — returns «4».

VBA Second Function

Use the VBA Second Function to return (Integer) the second of the minute from a given time — it returns a whole number between 0 and 59. Syntax: Second(time). The time argument can be a Variant, or a numeric or string expression, representing a valid time. VBA Code: MsgBox Second(«2:04:36 PM») — returns «36».

VBA WeekDay Function

Use the VBA Weekday Function to return (Integer) the day of the week from a given date — it returns a whole number. Syntax: Weekday(date, firstdayofweek). The date argument is necessary to specify, and it can be a Variant, or a numeric or string expression, representing a valid date. The firstdayofweek argument (optional) is a constant, specifying the first day of the week — Default is Sunday.

Constants to be used for the argument firstdayofweek: vbUseSystem (value 0) — use NLS API setting; vbSunday (this is the default) (value 1) — Sunday; vbMonday (value 2) — Monday; vbTuesday (value 3) — Tuesday; vbWednesday (value 4) — Wednesday; vbThursday (value 5) — Thursday; vbFriday (value 6) — Friday; vbSaturday (value 7) — Saturday.

Values returned by the VBA Weekday Function (Constant — value — Day): vbSunday — 1 — Sunday; vbMonday — 2 — Monday; vbTuesday — 3 — Tuesday; vbWednesday — 4 — Wednesday; vbThursday — 5 — Thursday; vbFriday — 6 — Friday; vbSaturday — 7 — Saturday.

VBA Code: MsgBox Weekday(#8/24/2012#) — returns «6» (representing a Friday)

VBA Code: MsgBox Weekday(#8/24/2012#, vbMonday) — returns «5» (representing a Friday — first day of week is set as Monday instead of Sunday)

VBA WeekdayName Function

Use the VBA WeekdayName Function to return the name of the weekday — it returns a String. Syntax: WeekdayName(weekday, abbreviate, firstdayofweek). The weekday argument is necessary to specify — it is a numeric value representing the day of the week, depending on the firstdayofweek setting. The abbreviate argument (optional) is a Boolean value wherein False (default) indicates that the weekday name should not be abbreviated. The firstdayofweek argument (optional) is a numeric value, specifying the first day of the week — Default is Sunday.

Values for the argument firstdayofweek: vbUseSystem (value 0) — use NLS API setting; vbSunday (this is the default) (value 1) — Sunday; vbMonday (value 2) — Monday; vbTuesday (value 3) — Tuesday; vbWednesday (value 4) — Wednesday; vbThursday (value 5) — Thursday; vbFriday (value 6) — Friday; vbSaturday (value 7) — Saturday.

VBA Code: MsgBox WeekdayName(6) — returns «Friday»

VBA Code: MsgBox WeekdayName(6, True) — returns «Fri»

VBA Code: MsgBox WeekdayName(6, False, vbMonday) — returns «Saturday», first day of week is set as Monday instead of Sunday

Using Find Method to Search for a Date

Using a Valid Excel Date and Format: Using the Find Method to Find or Search a Date can be tricky. The date format should correspond to the default date format as set in your desktop/Windows which, unless specifically changed, should be in its standard format of «Short Date» or «Long Date’, viz. «1/22/2010» or «January 22, 2010». It does not matter in which date format it is displayed in the worksheet, only it should be a valid Excel date equating to a valid serial number.

Example — Search for a date within a range — refer Image 1.

Sub FindMethod_SearchDate()
‘Search for a date within a range — refer Image 1.
‘user enters the date he wants to find in Range («D2») — he enters the serial number 41200 in this cell;

‘user wants to find the date in search Range («A1:A100») — the range «$A$5» is returned in this example because the serial number 41200 corresponds to the date 18-Oct-12 which is entered in cell A5.

Dim rngFound As Range, rngSearch As Range, rngLast As Range

Dim strDate As String

‘search range to find the date:

Set rngSearch = ActiveSheet.Range(«A1:A100«)

Set rngLast = rngSearch.Cells(rngSearch.Cells.Count)

‘user enters the date he wants to find in Range: ActiveSheet.Range(«D2»).

‘Format(«7/18/10», «Short Date») returns «7/18/2010»; Format(«7/18/10», «Long Date») returns «Sunday, July 18, 2010».

‘Format Function in vba: Display a date according to your system’s short date format using «Short Date»; and using «Long Date» displays a date according to your system’s long date format.

strDate = Format(ActiveSheet.Range(«D2«), «Short Date»)

‘The IsDate function returns True if the expression is a valid date, else it returns False.

If IsDate(strDate) = False Then

MsgBox «Incorrect Date Format»

Exit Sub

End If

‘CDate converts a number or text string to a Date data type. CDate(40200) returns «1/22/2010»; CDate(«October 15, 2009») returns «10/15/2009»; CDate(«2:25:15 PM») returns «2:25:15 PM»; CDate(«hello») returns an error.

Set rngFound = rngSearch.Find(What:=CDate(strDate), After:=rngLast, LookIn:=xlFormulas, LookAt:=xlWhole, SearchOrder:=xlByRows, SearchDirection:=xlNext, MatchCase:=False, SearchFormat:=False)

   
If Not rngFound Is Nothing Then

‘return range address ($A$5 — in this example) if date is found:

MsgBox rngFound.Address

Else

‘if date is not found in search range:

MsgBox «Date Not Found»

End If

End Sub

Date and Time Functions are the inbuilt functions that give us the opportunity to see the date or time according to the user’s need. Suppose a user needs to see the month or the day or the year then it can be easily seen by different date functions. Similarly, for the time function, also we can manipulate it according to the need of the user. Date and Time functions are used to interconvert date and time in different formats. In this article, we will learn about the most commonly used date and time functions.  

VBA Date Functions 

There are fifteen-plus different date functions in VBA, but here we will talk about some of the most commonly used date functions. 

VBA Date Function

The Date() function returns the current date. The Date() function does not require any arguments. For example, declare a variable name date_1 of Date data type, call the Date() function, and store the return value in date_1, then print the date_1 in the console. 

Syntax of the function: Date()

date function in vba

VBA DateAdd Function

The DateAdd() function is used to add an interval of date/time to the respective date or time. The function will return the resulting date or time. The function takes three arguments, Interval, Number, and Date/Time. 

Syntax of the function: DateAdd(Interval, Number, Date/Time)

Interval: The first argument, represents, which part of the Date/Time, you want the interval to be added. 

Types of intervals are discussed in the following table:

Intervals Specification
“d” Day
“ww” Week
“m” Month
“q” Quarter
“yyyy” Year
“y” Day of the year
“h” Hour
“n” Minute
“s” Second

Number: The second argument represents, the number of Intervals we want to add to the Date/Time.

Date/Time: The third argument represents, the Date/Time on which the changes have to occur. 

For example, the current date is “20/11/2020”, and we want to increase the month count by 8. Then use, DateAdd(“m”, 8, “20/11/2020”), and the final output date will be “20/07/2021”

DateAdd function in VBA

VBA DateDiff Function

The DateDiff() function is used to get the difference between two dates, in terms of the year, month, day, hours, seconds, etc. The function will return the resulting Date/Time. The functions take three mandatory arguments, Interval, Date1, and Date2. 

Syntax of the function: DateDiff(Interval, Date1, Date2)

Interval: The first argument, represents, the part of the Date/Time, you want to see the difference. For example, in terms of the year, day, month, etc. Refer to the table in VBADateAdd() function, for the values of Interval.  

Date1: Date1 is the second argument. It tells the start date in an interval. 

Date 2: Date2 is the third argument. It tells the end date in an interval. 

For example, consider Date1 as “20/10/2020”, and Date2 as “20/12/2021”, and the difference in terms of “d”(days). The final output of the function will be 426

datediff function in vba

VBA DatePart Function

The DatePart() function is used to get a particular part(day, week, year) from the date. The function returns the part of date in asked format by the user. The function takes two mandatory arguments, Interval, Date. 

Syntax of the function: DatePart(Interval, Date)

Interval:  The first argument, represents, the part of the Date/Time, one wants to see. For example, “yyyy” represents the year, and tells the DatePart function to return the year of an input Date. 

Date: The second argument, which represents the date user will enter, to check a particular part of a date. 

For example, consider the Date as “10/10/2020”, and it has been asked to print the year of this particular date. So, we will use “yyyy” as the first argument. The final output is 2020

datepart function in vba

VBA MonthName Function

The MonthName() function returns the name of the month according to the integer value. The function takes one mandatory argument, a number. 

Syntax of the function: MonthName(number)

number: The first argument, which tells about the number of the month. 

For example, 11 is the argument of the MonthName() function, the function returns “November”

monthname function in vba

VBA Time Functions

There are ten-plus different time functions in VBA, but here we will talk about some of the most commonly used time functions. 

VBA Now Function

The Now() function is used to get the current date and time of the system. The function does not take any arguments. For example, declare a variable name date_2 of Date data type, call the Now() function, and store the return value in date_2, then print the date_2 in the console. 

Syntax of the function: Now()

now function in vba

VBA Time Function

The Time() function is used to get the current time of your system. The function does not take any arguments. For example, call the Time() function, and the system will return the current time i.e. 5:20:20 PM.

Syntax of the function: Time()

time function in vba

VBA Hour Function

The hour() function is used to get the hour from the time. The function takes one mandatory argument, Time. 

Syntax of the function: hour(Time)

Time: The first argument, which represents the time user will enter. 

For example, consider the time “1:08:42 PM”, and it has been asked to print the hour of this particular time. The final output will be 1

hour function in vba

VBA Minute Function 

The minute() function is used to get the minute from the time. The function takes one mandatory argument, Time.

Syntax of the function: minute(Time)

Time: The first argument, which represents the time user will enter.

For example, consider the time “1:08:42 PM”, and it has been asked to print the minute of this particular time. The final output will be 08

minute function in vba

VBA Second Function

The second() function is used to get the seconds from the time. The function takes one mandatory argument, Time.

Syntax of the function: second(Time)

Time: The first argument, which represents the time user will enter.

For example, consider the time “1:08:42 PM”, and it has been asked to print the seconds of this particular time. The final output will be 42

second function in vba

In this Article

  • VBA Date Function
  • VBA Now Function
  • VBA Time Function
  • VBA DateAdd Function
  • VBA DateDiff Function
  • VBA DatePart Function
  • VBA DateSerial Function
  • VBA DateValue Function
  • VBA Day Function
  • VBA Hour Function
  • VBA Minute Function
  • VBA Second Function
  • VBA Month Function
  • VBA MonthName Function
  • VBA TimeSerial Function
  • VBA TimeValue Function
  • VBA Weekday Function
  • VBA WeekdayName Function
  • VBA Year Function
  • Comparing Dates in VBA

This tutorial will cover the different built-in VBA Date Functions.

VBA Date Function

You can use the Date Function to return the current date.

The syntax of the Date Function is Date(). It has no arguments.

The following code shows you how to use the Date Function:

Sub UsingTheDateFunction()

Dim theDate As Date
theDate = Date()

Debug.Print theDate

End Sub

The result shown in the Immediate Window is:

Using the Date Function in VBA

VBA Now Function

You can use the Now Function to return the current date and time.

The syntax of the Now Function is Now(). It has no arguments.

The following code shows you how to use the Now Function:

Sub UsingTheNowFunction()

Dim theDate As Date
theDate = Now()

Debug.Print theDate

End Sub

The result is:

Using the Now Function in VBA

VBA Time Function

You can use the Time Function to return the current time.

The syntax of the Time Function is Time(). It has no arguments.

The following code shows you how to use the Time Function:

Sub UsingTheTimeFunction()

Dim theTime As Date
theTime = Time()

Debug.Print theTime

End Sub

The result is:

Using the Time Function in VBA

VBA DateAdd Function

You can use the DateAdd Function to add a date/time interval to a date or time, and the function will return the resulting date/time.

The syntax of the DateAdd Function is:

DateAdd(Interval, Number, Date) where:

  • Interval – A string that specifies the type of interval to use. The interval can be one of the following values:

“d” – day
“ww” – week
“w” – weekday
“m” – month
“q” – quarter
“yyyy” – year
“y” – day of the year
“h” – hour
“n” – minute
“s” – second

  • Number – The number of intervals that you want to add to the original date/time.
  • Date – The original date/time.

Note: When using dates in your code you have to surround them with # or quotation marks.

The following code shows  how to use the DateAdd Function:

Sub UsingTheDateAddFunction()

Dim laterDate As Date

laterDate = DateAdd("m", 10, "11/12/2019")

Debug.Print laterDate

End Sub

The result is:

Using the DateAdd Function in VBA

VBA DateDiff Function

You can use the DateDiff Function in order to get the difference between two dates, based on a specified time interval.

The syntax of the DateDiff Function is:

DateDiff(Interval, Date1, Date2, [Firstdayofweek], [Firstweekofyear]) where:

  • Interval – A string that specifies the type of interval to use. The interval can be one of the following values:

“d” – day
“ww” – week
“w” – weekday
“m” – month
“q” – quarter
“yyyy” – year
“y” – day of the year
“h” – hour
“n” – minute
“s” – second

  • Date1 – A date value representing the earlier date.
  • Date2 – A date value representing the later date.
  • Firstdayofweek (Optional) – A constant that specifies the weekday that the function should use as the first day of the week. If blank Sunday is used as the first day of the week. Firstdayofweek can be one of the following values:

-vbSunday – uses Sunday as the first day of the week.
-vbMonday – uses Monday as the first day of the week.
-vbTuesday – uses Tuesday as the first day of the week.
-vbWednesday – uses Wednesday as the first day of the week.
-vbThursday – uses Thursday as the first day of the week.
-vbFriday – uses Friday as the first day of the week.
-vbSaturday – uses Saturday as the first day of the week.
-vbUseSystemDayOfTheWeek – uses the first day of the week that is specified by your system’s settings.

  • Firstweekofyear (Optional) – A constant that specifies the first week of the year. If blank then the Jan 1st week is used as the first week of the year. Firstweekofyear can be one of the following values:

-vbFirstJan1 – uses the week containing Jan 1st.
-vbFirstFourDays – uses the first week that contains at least four days in the new year.
-vbFirstFullWeek – uses the first full week of the year.
-vbSystem – uses the first week of the year as specified by your system settings.

The following code shows you how to use the DateDiff Function:

Sub UsingTheDateDiffFunction()
 
Dim theDifferenceBetweenTwoDates As Long
 
theDifferenceBetweenTwoDates = DateDiff("q", "11/11/2010", "10/12/2012")
 
Debug.Print theDifferenceBetweenTwoDates
 
End Sub

The result is:

Using The DateDiff Function in VBA

VBA DatePart Function

You can use the DatePart Function in order to return a part (day, week, quarter, month etc.) of a given date.

The syntax of the DatePart Function is:

DatePart(Interval, Date,[Firstdayofweek], [Firstweekofyear]) where:

  • Interval – A string that specifies the part of the date to return. The interval can be one of the following values:

“d” – day
“ww” – week
“w” – weekday
“m” – month
“q” – quarter
“yyyy” – year
“y” – day of the year
“h” – hour
“n” – minute
“s” – second

  • Date – The date that you want the function to return a part of.
  • Firstdayofweek (Optional) – A constant that specifies the weekday that the function should use as the first day of the week. If blank Sunday is used as the first day of the week. Firstdayofweek can be one of the following values:

-vbSunday – uses Sunday as the first day of the week.
-vbMonday – uses Monday as the first day of the week.
-vbTuesday – uses Tuesday as the first day of the week.
-vbWednesday – uses Wednesday as the first day of the week.
-vbThursday – uses Thursday as the first day of the week.
-vbFriday – uses Friday as the first day of the week.
-vbSaturday – uses Saturday as the first day of the week.
-vbUseSystemDayOfTheWeek – uses the first day of the week that is specified by your system’s settings.

  • Firstweekofyear (Optional) – A constant that specifies the first week of the year. If blank then the Jan 1st week is used as the first week of the year. Firstweekofyear can be one of the following values:

-vbFirstJan1 – uses the week containing Jan 1st.
-vbFirstFourDays – uses the first week that contains at least four days in the new year.
-vbFirstFullWeek – uses the first full week of the year.
-vbSystem – uses the first week of the year as specified by your system settings.

The following code shows you how to use the DatePart Function:

Sub UsingTheDatePartFunction()

Dim thePartOfTheDate As Integer

thePartOfTheDate = DatePart("yyyy", "12/12/2009")

Debug.Print thePartOfTheDate

End Sub

The result is:

Using the DatePart Function in VBA

VBA Coding Made Easy

Stop searching for VBA code online. Learn more about AutoMacro — A VBA Code Builder that allows beginners to code procedures from scratch with minimal coding knowledge and with many time-saving features for all users!

automacro

Learn More

VBA DateSerial Function

The VBA DateSerial Function takes an input year, month and day and returns a date.

The syntax of the DateSerial Function is:

DateSerial(Year,  Month, Day) where:

  • Year – An integer value between 100 and 9999 that represents the year.
  • Month – An integer value that represents the month.
  • Day – An integer value that represents the day.

The following code shows you how to use the DateSerial Function:

Sub UsingTheDateSerialFunction()

Dim theDate As Date

theDate = DateSerial(2010, 11, 10)

Debug.Print theDate

End Sub

The result is:

Using the Date Serial Function in VBA

VBA DateValue Function

The DateValue Function returns a Date when given a string representation of a date.

The syntax of the DateValue Function is:

DateValue(Date) where:

  • Date – A String representing the date.

The following code shows you how to use the DateValue Function:

Sub UsingTheDateValueFunction()

Dim theDate As Date

theDate = DateValue("October, 29, 2010")

Debug.Print theDate

End Sub

The result is:

Using the DateValue Function in VBA

VBA Day Function

You can use the Day Function to return the day of an input date.

The syntax of the Day Function is:

Day(Date_value) where:

  • Date_value – The date which you want to extract the day from.

The following code shows you how to use the Day Function:

Sub UsingTheDayFunction()

Dim theDay As Integer

theDay = Day("10/12/2010")

Debug.Print theDay

End Sub

The result is:

Using the Day Function in VBA

VBA Programming | Code Generator does work for you!

VBA Hour Function

You can use the Hour Function to return the hour of an input time.

The syntax of the Hour Function is:

Hour(Time) where:

  • Time – The time that you want to extract the hour from.

The following code shows you how to use the Hour Function:

Sub UsingTheHourFunction()
 
Dim theHour As Integer

theHour = Hour("2:14:17 AM")

Debug.Print theHour

End Sub

The result is:

Using the Hour Function in VBA

VBA Minute Function

You can use the Minute Function to return the minute value of an input time.

The syntax of the Minute Function is:

Minute(Time) where:

  • Time – The time that you want to extract the minute value from.

The following code shows you how to use the Minute Function:

Sub UsingTheMinuteFunction()
 
Dim theMinuteValue As Integer

theMinuteValue = Minute("2:14:17 AM")

Debug.Print theMinuteValue

End Sub

The result is:

Using The Minute Function in VBA

VBA Second Function

You can use the Second Function to return the second value of an input time.

The syntax of the Second Function is:

Second(Time) where:

  • Time – The time that you want to extract the second value from.

The following code shows you how to use the Second Function:

Sub UsingTheSecondFunction()
 
Dim theSecondValue As Integer

theSecondValue = Second("2:14:17 AM")

Debug.Print theSecondValue

End Sub

The result is:

Using the Second Function in VBA

VBA Month Function

You can use the Month Function to return the month of an input date.

The syntax of the Month Function is:

Month(Date_value) where:

  • Date_value – The date which you want to extract the month from.

The following code shows you how to use the Month Function:

Sub UsingTheMonthFunction()
 
Dim theMonth As Integer

theMonth = Month("11/18/2010")
Debug.Print theMonth

End Sub

The result is:

Using the Month Function in VBA

VBA MonthName Function

You can use the MonthName Function to return the name of a month from an input supplied month number.

The syntax of the MonthName Function is:

MonthName(Number_of_month, [Abbreviate]) where:

  • Number_of_month – An integer value between 1 and 12.
  • Abbreviate (Optional) – Specifies whether the month name should be abbreviated. If blank the default value of False is used.
Sub UsingTheMonthNameFunction()
 
Dim theMonthName As String

theMonthName = MonthName(12, True)
Debug.Print theMonthName

End Sub

The result is:

AutoMacro | Ultimate VBA Add-in | Click for Free Trial!

VBA TimeSerial Function

The TimeSerial Function takes an input hour, minute and second and returns a time.

The syntax of the TimeSerial Function is:

TimeSerial(Hour,  Minute, Second) where:

  • Hour – An integer value between 0 and 23 that represents the hour value.
  • Minute – An integer value between 0 and 59 that represents the minute value.
  • Second – An integer value between 0 and 59 that represents the second value.

The following code shows you how to use the TimeSerial Function:

Sub UsingTheTimeSerialFunction()

Dim theTime As Date
theTime = TimeSerial(1, 10, 15)

Debug.Print theTime

End Sub

The result is:

Using the TimeSerial Function in VBA

VBA TimeValue Function

The TimeValue Function returns a Time from a string representation of a date or time.

The syntax of the TimeValue Function is:

TimeValue(Time) where:

  • Time – A String representing the time.

The following code shows you how to use the TimeValue Function:

Sub UsingTheTimeValueFunction()

Dim theTime As Date
theTime = TimeValue("22:10:17")

Debug.Print theTime

End Sub

The result is:

The Time Value Function in VBA

VBA Weekday Function

You can use the Weekday Function to return an integer from 1 – 7 representing a day of the week from an input date.

The syntax of the Weekday Function is:

Weekday(Date, [Firstdayofweek]) where:

  • Date – The date that you want to extract the weekday value from.
  • Firstdayofweek (Optional) – A constant that specifies the weekday that the function should use as the first day of the week. If blank Sunday is used as the first day of the week. Firstdayofweek can be one of the following values:

-vbSunday – uses Sunday as the first day of the week.
-vbMonday – uses Monday as the first day of the week.
-vbTuesday – uses Tuesday as the first day of the week.
-vbWednesday – uses Wednesday as the first day of the week.
-vbThursday – uses Thursday as the first day of the week.
-vbFriday – uses Friday as the first day of the week.
-vbSaturday – uses Saturday as the first day of the week.
-vbUseSystemDayOfTheWeek – uses the first day of the week that is specified by your system’s settings.

The following code shows you how to use the Weekday Function:

Sub UsingTheWeekdayFunction()

Dim theWeekDay As Integer
theWeekDay = Weekday("11/20/2019")
Debug.Print theWeekDay

End Sub

The result is:

Using The WeekDay Function in VBA

VBA WeekdayName Function

You can use the WeekdayName Function to return the name of a weekday from an input supplied weekday number.

The syntax of the WeekdayName Function is:

WeekdayName(Weekday, [Abbreviate], [Firstdayoftheweek]) where:

  • Weekday – An integer value between 1 and 7.
  • Abbreviate (Optional) -Specifies whether the weekday name should be abbreviated. If blank the default value of False is used.
  • Firstdayofweek (Optional) – A constant that specifies the weekday that the function should use as the first day of the week. If blank Sunday is used as the first day of the week. Firstdayofweek can be one of the following values:

-vbSunday – uses Sunday as the first day of the week.
-vbMonday – uses Monday as the first day of the week.
-vbTuesday – uses Tuesday as the first day of the week.
-vbWednesday – uses Wednesday as the first day of the week.
-vbThursday – uses Thursday as the first day of the week.
-vbFriday – uses Friday as the first day of the week.
-vbSaturday – uses Saturday as the first day of the week.
-vbUseSystemDayOfTheWeek – uses the first day of the week that is specified by your system’s settings.

Sub UsingTheWeekdayNameFunction()
 
Dim theWeekdayName As String

theWeekdayName = WeekdayName(4)
Debug.Print theWeekdayName

End Sub

The result is:

Using the WeekdayName Function in VBA

AutoMacro | Ultimate VBA Add-in | Click for Free Trial!

VBA Year Function

You can use the Year Function to return the year of an input date.

The syntax of the Year Function is:

Year(Date_value) where:

  • Date_value – The date which you want to extract the year from.

The following code shows you how to use the Year Function:

Sub UsingTheYearFunction()

Dim theYear As Integer

theYear = Year("11/12/2010")
Debug.Print theYear

End Sub

The result is:

Using The Year Function in VBA

Comparing Dates in VBA

You can compare dates using the >, <, and = operators in VBA. The following code shows you how to compare two dates in VBA.

Sub ComparingDates()

Dim dateOne As Date
Dim dateTwo As Date

dateOne = "10/10/2010"
dateTwo = "11/11/2010"

If dateOne > dateTwo Then
Debug.Print "dateOne is the later date"

ElseIf dateOne = dateTwo Then
Debug.Print "The two dates are equal"

Else
Debug.Print "dateTwo is the later date"

End If
End Sub

Comparing Dates in VBA

Learn more about how to Format dates as strings by viewing this tutorial.

Home / VBA / How to Get Today’s Date and Current Time using VBA

In this tutorial, we will learn different ways to get today’s date and current time using a VBA code.

In VBA, there’s a function called “DATE” that you can use to get the current date. When you use this function, just like the following example, it returns the current date according to the date setting of the system.

Sub myMacro()
Range("A1") = Date
End Sub

When you run this code, it enters the current date into cell A1 and uses the current format of the date that you have in Excel.

today-date-in-vba

You can also use this function to get today’s date into a message box, just like the following code.

Sub myMacro()
MsgBox Date
End Sub

Today’s Date and Current Time

In the same way, there’s a function called “NOW” that you can use to get today’s date and current time. As you can see, we have used it in the following code to get the current date and time into cell A1.

today-date-and-current-time
Sub myMacro()
Range("A1") = Now
End Sub

Current Time

Now if you want to get the current time only instead of date and time you need to use another function “Format” (you can learn more about this function from here) along with the now function.

current-time

In the above code, we have used the now function to provide the value for the format function and then used a format for the time only.

Sub myMacro()
Range("A1") = Format(Now, "HH:MM Am/Pm")
End Sub

Changing Today’s Date Format (Example: YYYYMMDD)

You can also use the format function to change the format of the current date. In the following code, we have used the format function and specify the format as “YYYYMMDD”.

Sub myMacro()
Range("A1").Value = Format(Date, "YYYY/MM/DD")
End Sub

Note: In the above code, we have used value property to enter the date into cell A1.

today-date-format

VBA Date and Time Functions in Excel. VBA Date and Time Functions help us to convert date and time from one format to another. These are DATE, DATEDIFF, DATEPART, DATESERIAL, DATEVALUE, DAY, HOUR, MINUTE, MONTH, NOW, TIME, TIMESERIAL, TIMEVALUE etc. Date & Time functions are Built-In functions. We can use these VBA Date and Time functions in either procedure or function. These functions we use in the VBA editor window in Excel. These Date and Time functions you can use any number of times in VBA macro codes.

List of Date and Time Functions in Excel VBA:

Here are the list of Date and Time functions. And also find its description, syntax and return type. We can use these multiple Date and Time functions in one statement.

Function Description Syntax Return Type
VBA Date VBA Date function returns current system date. Date() Date
VBA DateAdd VBA DateAdd function returns a date after which a certain time or date interval has been added. DateAdd(Interval, Number, Date) String
VBA DateDiff VBA DateDiff function returns the difference between two date values. It depends on the specified interval. DateDiff (Interval,Date1,Date2, FirstDayOfWeek,FirstWeekOfYear) Long
VBA DatePart VBA DatePart function returns a specified part of a supplied date or time DatePart(interval,date, [firstdayofweek],[firstweekofyear]) Integer
VBA DateSerial VBA DateSerial function returns date. DateSerial(year, month, day) Date
VBA DateValue VBA DateValue function returns the date value for specified string input. DateValue(date_value) Date
VBA Day VBA Day function returns day from date. Day(date_value) Integer
VBA Hour VBA Hour function returns hour from time. Hour(time_value) Integer
VBA Minute VBA Minute function returns Minute from time. Minute(time_value Integer
VBA Month VBA Month function returns month from date. Month(date_value) Integer
VBA MonthName VBA MonthName function returns a string representing the month given a number from 1 to 12. MonthName(Month,[Abbreviate]) String
VBA Now VBA Now function returns system date and time. Now() Date
VBA Time VBA Time function returns current system time. Time() Date
VBA TimeSerial VBA TimeSerialfunction returns time. TimeSerial(hour, minute, second) Date
VBA TimeValue VBA TimeValue function returns the date value for specified input represents date. TimeValue(time_value) Date
VBA Weekday VBA Weekday function returns a number representing the day of the week, given a date value. Weekday(Date,[FirstDayOfWeek]) Integer
VBA WeekdayName VBA WeekdayName function returns a string representing the day of the week given a number from 1 to 7. WeekdayName(Weekday,[Abbreviate],[FirstDayOfWeek]) String
VBA Year VBA Year function returns year from date. Year(date_value) Integer

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

# Calendar

VBA supports 2 calendars : Gregorian (opens new window) and Hijri (opens new window)

The Calendar property is used to modify or display the current calendar.

The 2 values for the Calendar are:

Value Constant Description
0 vbCalGreg Gregorian calendar (default)
1 vbCalHijri Hijri calendar

# Example

This Sub prints the following ;

# Base functions

# Retrieve System DateTime

VBA supports 3 built-in functions to retrieve the date and/or time from the system’s clock.

Function Return Type Return Value
Now Date Returns the current date and time
Date Date Returns the date portion of the current date and time
Time Date Returns the time portion of the current date and time

# Timer Function

The Timer function returns a Single representing the number of seconds elapsed since midnight. The precision is one hundredth of a second.

Because Now and Time functions are only precise to seconds, Timer offers a convenient way to increase accuracy of time measurement:

# IsDate()

IsDate() tests whether an expression is a valid date or not. Returns a Boolean.

These functions take a Variant that can be cast to a Date as a parameter and return an Integer representing a portion of a date or time. If the parameter can not be cast to a Date, it will result in a run-time error 13: Type mismatch.

Function Description Returned value
Year() Returns the year portion of the date argument. Integer (100 to 9999)
Month() Returns the month portion of the date argument. Integer (1 to 12)
Day() Returns the day portion of the date argument. Integer (1 to 31)
WeekDay() Returns the day of the week of the date argument. Accepts an optional second argument definining the first day of the week Integer (1 to 7)
Hour() Returns the hour portion of the date argument. Integer (0 to 23)
Minute() Returns the minute portion of the date argument. Integer (0 to 59)
Second() Returns the second portion of the date argument. Integer (0 to 59)

Examples:

# DatePart() Function

DatePart() is also a function returning a portion of a date, but works differently and allow more possibilities than the functions above. It can for instance return the Quarter of the year or the Week of the year.

Syntax:

interval argument can be :

Interval Description
«yyyy» Year (100 to 9999)
«y» Day of the year (1 to 366)
«m» Month (1 to 12)
«q» Quarter (1 to 4)
«ww» Week (1 to 53)
«w» Day of the week (1 to 7)
«d» Day of the month (1 to 31)
«h» Hour (0 to 23)
«n» Minute (0 to 59)
«s» Second (0 to 59)

firstdayofweek is optional. it is a constant that specifies the first day of the week. If not specified, vbSunday is assumed.

firstweekofyear is optional. it is 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.

Examples:

# Calculation functions

# DateDiff()

DateDiff() returns a Long representing the number of time intervals between two specified dates.

Syntax

  • interval can be any of the intervals defined in the DatePart() (opens new window) function
  • date1 and date2 are the two dates you want to use in the calculation
  • firstdayofweek and firstweekofyear are optional. Refer to DatePart() (opens new window) function for explanations

Examples

# DateAdd()

DateAdd() returns a Date to which a specified date or time interval has been added.

Syntax

  • interval can be any of the intervals defined in the DatePart() (opens new window) function
  • number 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 is a Date or literal representing date to which the interval is added

Examples :

# Conversion and Creation

# CDate()

CDate() converts something from any datatype to a Date datatype

Note that VBA also has a loosely typed CVDate() that functions in the same way as the CDate() function other than returning a date typed Variant instead of a strongly typed Date. The CDate() version should be preferred when passing to a Date parameter or assigning to a Date variable, and the CVDate() version should be preferred when when passing to a Variant parameter or assigning to a Variant variable. This avoids implicit type casting.

# DateSerial()

DateSerial() function is used to create a date. It returns a Date for a specified year, month, and day.

Syntax:

With year, month and day arguments being valid Integers (Year from 100 to 9999, Month from 1 to 12, Day from 1 to 31).

Examples

Note that DateSerial() will accept «invalid» dates and calculate a valid date from it. This can be used creatively for good:

Positive Example

However, it is more likely to cause grief when attempting to create a date from unvalidated user input:

Negative Example

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

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

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

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

Like this post? Please share to your friends:
  • Vba excel thisworkbook worksheets
  • Vba excel this year
  • Vba excel this sheet name
  • Vba excel this book
  • Vba excel then do the