Datevalue in excel vba

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

Функция Date

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

Синтаксис

Пример

Sub PrimerDate()

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

End Sub

Функция DateAdd

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

Синтаксис

DateAdd(interval, number, date)

Параметры

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

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

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

Пример

Sub PrimerDateAdd()

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

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

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

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

End Sub

Функция DateDiff

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

Синтаксис

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

Параметры

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

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

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

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

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

Пример

Sub PrimerDateDiff()

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

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

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

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

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

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

End Sub

Функция DatePart

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

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

Синтаксис

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

Параметры

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

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

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

Пример

Sub PrimerDatePart()

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

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

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

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

End Sub

Функция DateSerial

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

Синтаксис

DateSerial(year, month, day)

Параметры

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

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

Пример

Sub PrimerDateSerial()

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

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

End Sub

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

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

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

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

Функция DateValue

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

Синтаксис

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

Пример

Sub PrimerDateValue()

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

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

End Sub

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

Функция Day

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

Синтаксис

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

Пример

Sub PrimerDay()

    MsgBox Day(Now)

End Sub

Функция IsDate

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

Синтаксис

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

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

Пример

Sub PrimerIsDate()

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

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

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

End Sub

Функция Hour

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

Синтаксис

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

Пример

Sub PrimerHour()

    MsgBox Hour(Now)

    MsgBox Hour(«22:36:54»)

End Sub

Функция Minute

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

Синтаксис

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

Пример

Sub PrimerMinute()

    MsgBox Minute(Now)

    MsgBox Minute(«22:36:54»)

End Sub

Функция Month

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

Синтаксис

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

Пример

Sub PrimerMonth()

    MsgBox Month(Now)

End Sub

Функция MonthName

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

Синтаксис

MonthName(month, [abbreviate])

Параметры

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

Пример

Sub PrimerMonthName()

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

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

End Sub

Функция Now

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

Синтаксис

Пример

Sub PrimerNow()

    MsgBox Now

    MsgBox Day(Now)

    MsgBox Hour(Now)

End Sub

Функция Second

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

Синтаксис

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

Пример

Sub PrimerSecond()

    MsgBox Second(Now)

    MsgBox Second(«22:30:14»)

End Sub

Функция Time

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

Синтаксис

Пример

Sub PrimerTime()

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

End Sub

Функция TimeSerial

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

Синтаксис

TimeSerial(hour, minute, second)

Параметры

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

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

Пример

Sub PrimerTime()

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

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

End Sub

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

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

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

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

Функция TimeValue

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

Синтаксис

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

Пример

Sub PrimerTimeValue()

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

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

End Sub

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

Функция Weekday

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

Синтаксис

Weekday(date, [firstdayofweek])

Параметры

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

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

Пример

Sub PrimerWeekday()

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

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

End Sub

Функция WeekdayName

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

Синтаксис

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

Параметры

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

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

Пример

Sub PrimerWeekdayName()

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

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

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

End Sub

Функция Year

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

Синтаксис

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

Пример

Sub PrimerYear()

    MsgBox Year(Now)

End Sub

Приложение 1

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

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

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

Приложение 2

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

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

Приложение 3

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

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

VBA DateValue

VBA DateValue Function

While working in VBA we work with dates. We assign dates to various variables or we can use the DATEVALUE function to do so. DATEVALUE is both worksheet and Visual Basic function. In worksheet, it gives a serial date. When we use this function in VBA it gives us a date value. As I told above the DATEVALUE function used in VBA returns a date value. The data type we used for our variables while using this function is date. It is somewhat similar to the worksheet function. How we use this function is pretty simple, it takes a date as an argument.

Syntax of DateValue in Excel VBA

The syntax for the VBA DateValue Function in excel is as follows:

Syntax of VBA DateValue

What this function does that it takes a value or an argument as a string and returns it to a date. Why we use this function is because we work with lots of data and every human being is not similar so there will be a difference in entering date formats for each and every different person. If we have to do some calculations over the dates on the data then we will have to convert every different format of the dates available in the data onto one single format and then perform the calculation. Now imagine the large chunk of data with a large chunk of different types of dates.

Let us look by a few examples of how we can use this DATEVALUE function in VBA through some examples which will give us some more clear idea on how this function works.

How to Use VBA DateValue in Excel?

We will learn how to use a VBA DateValue Function with few examples in excel.

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

Example #1 – VBA DateValue

Let us begin with a very simple step. We will assign a variable a date value as a string and then print the date value for that variable.

Step 1: Now once we are inside the editor we will have a lot of options in the header, from the insert tab insert a new module in the editor where we will perform all the example demonstrations,

DateValue Module

Step 2: Now let us start our procedure as shown below.

Code:

Sub Sample()

End Sub

Datevalue Example 1.1

Step 3: Let us declare a variable as Date data type as shown below,

Code:

Sub Sample()

Dim A As Date

End Sub

Datevalue Example 1.2

Step 4: Now let us provide variable A with some value using the DATEVALUE function as shown below.

Code:

Sub Sample()

Dim A As Date
A = DateValue("02/02/2019")

End Sub

vba datevalue function Example 1.3

Step 5: I have provided the date in double inverted commas to treat it as a string, now use the msgbox function to display the value stored in A.

Code:

Sub Sample()

Dim A As Date
A = DateValue("02/02/2019")
MsgBox A

End Sub

vba datevalue function Example 1.4

Step 6: Execute the above code and see the result.

VBA DateValue 1

We know that in VBA date is provided in # symbols and a string is provided in “ double quotes. But DATEVALUE changes the value to date.

Example #2 – VBA DateValue

Now let us take an input from a user in date because a user can provide a date in any format. We will convert the value given by the user in the date using the DATEVALUE function.

Step 1: From the Insert, select a new module in the editor.

vba datevalue function Module 2

Step 2: Now let us start another subprocedure as follows.

Code:

Sub Sample1()

End Sub

Datevalue Example 2.1

Step 3: Declare two variables as dates as we will take value from input from user in one variable while in another we will use the DATEVALUE function to convert it to a date.

Code:

Sub Sample1()

Dim InputDate As Date, OutputDate As Date

End Sub

Example 2.2

Step 4: In the input data variable take the input from the user using the input box function.

Code:

Sub Sample1()

Dim InputDate As Date, OutputDate As Date
InputDate = InputBox("Enter a Date")

End Sub

Example 2.3

Step 5: In the Outputdate variable let us change the date we get as input to date using the DATEVALUE function as shown below.

Code:

Sub Sample1()

Dim InputDate As Date, OutputDate As Date
InputDate = InputBox("Enter a Date")
OutputDate = DateValue(InputDate)

End Sub

Example 2.4

Step 6: Now let us display the value we have now using the msgbox function.

Code:

Sub Sample1()

Dim InputDate As Date, OutputDate As Date
InputDate = InputBox("Enter a Date")
OutputDate = DateValue(InputDate)
MsgBox OutputDate

End Sub

Datevalue Example 2.5

Step 7: Run the above code and give an input date as follows.

Output 1

Step 8: Click on OK and see the final result as follows.

Output 2

Although the date format from the user was different still we have successfully converted it into a date.

Example #3 – VBA DateValue

We can see dates in our sheet and how to use DATEVALUE function on them? I have a date in cell A1 as follows.

Datevalue Example 3.1

Let us change it to the standard date we have.

Step 1: Again in the same module start another subprocedure as shown below.

Code:

Sub Sample2()

End Sub

vba datevalue function Example 3.2

Step 2: Declare a variable as Date as shown below.

Code:

Sub Sample2()

Dim Dt As Date

End Sub

Example 3.3

Step 3: Now in the Dt variable, store the value of the cell A1 which is as follows using the DATEVALUE function.

Code:

Sub Sample2()

Dim Dt As Date
Dt = DateValue(Sheet1.Range("A1").Value)

End Sub

Example 3.4

Step 4: Now let us display the value stored in our variable.

Code:

Sub Sample2()

Dim Dt As Date
Dt = DateValue(Sheet1.Range("A1").Value)
MsgBox Dt

End Sub

vba datevalue function Example 3.5

Step 5: Now execute the above code and let us see the result.

VBA DateValue 2

Things to Remember

  • DATEVALUE is a date function in VBA.
  • It is somewhat similar to the worksheet function, worksheet function gives us the serial numbers of the date while in VBA it gives us the DATEVALUE.
  • This function takes the argument as the date in the string and converts it in the string.

Recommended Articles

This is a guide to VBA DateValue. Here we discuss how to use Excel VBA DateValue Function along with practical examples and downloadable excel template. You can also go through our other suggested articles –

  1. VBA Copy Paste
  2. VBA Date Format
  3. VBA Subscript out of Range
  4. VBA Web Scraping

What is VBA DateValue Function?

A DateValue function is a built-in function in Excel VBA under the Date/Time function category. It works as both the VBA functionVBA functions serve the primary purpose to carry out specific calculations and to return a value. Therefore, in VBA, we use syntax to specify the parameters and data type while defining the function. Such functions are called user-defined functions.read more and worksheet function in VBAThe worksheet function in VBA is used when we need to refer to a specific worksheet. When we create a module, the code runs in the currently active sheet of the workbook, but we can use the worksheet function to run the code in a particular worksheet.read more. This function returns the serial number or value of the date provided in the string representation format ignoring the information of time supplied by the date string. One can use it in two different ways in Excel. First, one may use this function as a worksheet formula entering a worksheet cell. It is used as the macro code in the VBA application, entering it through Visual Basic Editor associated with Microsoft Excel.

In this article, we will learn examples of the VBA DateValue function and how to use it with a clear explanation.

Table of contents
  • What is VBA DateValue Function?
    • Explanation of VBA Datevalue Function
    • How to Use Excel VBA DATEVALUE?
    • Examples of Excel VBA DATEVALUE
      • Example #1 – Obtain Day, Month, and Year from a Date
      • Example #2 – Using the DatePart to Get the Different Parts of Date
    • Things to Remember About the VBA DATEVALUE
    • Recommended Articles

VBA DateValue - updated

Explanation of VBA Datevalue Function

In VBA, the DateValue function uses the following syntax.

VBA DateValue Formula

This function uses only a single argument or parameter:

  • Date: It is the date represented in the string format.
  • Returns: This function returns the value of the date when used as a VBA function. It returns the date value when used as a worksheet function.

The VBA DateValue function can interpret data represented in text format mentioned in a valid Excel format. However, it cannot return the date value if the string includes the text representation of weekdays.

The benefits of the VBA DateValue function are extracting date value from string and converting date with time to the only date. So, we can simplify that when we give a date with time, this function only gives the date value avoiding the time value.

How to Use Excel VBA DATEVALUE?

First, open the VBA editorThe Visual Basic for Applications Editor is a scripting interface. These scripts are primarily responsible for the creation and execution of macros in Microsoft software.read more to use the DateValue function in Excel.

The command button needs to be placed in the Excel worksheet to add the lines of the VBA program. To implement the program lines, the user must click on the Excel sheet’s “Command Button.” Valid input is given through the argument to have a valid output from the program. For example, the following code helps the creation of a macro to run the DateValue function to extract the date value from the text in VBAText is a worksheet function in excel but it can also be used in VBA while using the range property. It is similar to the worksheet function and it takes the same number of arguments. These arguments are the values which needs to be converted.read more.

VBA program: 

Sub Datebutton ()

Dim myDate As Date

myDate = DateValue (“ August 15, 1991”)

MsgBox Date (myDate)

End Sub

This code results in the date as 15 from the given input.

Examples of Excel VBA DATEVALUE

Below are the examples of DateValue in Excel VBA.

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

Example #1 – Obtain Day, Month, and Year from a Date

We must follow a few steps to create and execute the program in VBA. Those include:

Step 1: Go to the “Developer” tab.

  • Place the cursor on a cell in the Excel sheet.
  • Click on the “Insert” option.
  • Choose “Command Button” under “ActiveX Control,” as shown in the figure.

VBA Datevalue Example 1

Drag the button where you want and give the caption as “Datebutton” from the “Properties” window.

VBA Datevalue Example 1-1

Step 2: Double click on the button. It will redirect to the VBA project and write the code between the “Private Sub-command button” and the “End sub.”

One should develop the code below to get a date, month, and year.

Code:

Private Sub Datebutton1_Click()

  Dim Exampledate As Date

  Exampledate = DateValue("April 19,2019")
  MsgBox Date
  MsgBox Year(Exampledate)
  MsgBox Month(Exampledate)

End Sub

VBA Datevalue Example 1-2

In this code, Datebutton1_Click() is the name, and example dates are variable with Date data type and Msgbox to display the output.

Step 3: While developing code, VBA type mismatch errorsWhen we assign a value to a variable that is not of its data type, we get Type mismatch Error or Error code 13. For example, if we assign a decimal or long value to an integer data type variable, we will get this error (Error Code 13) when we run the code.read more will occur and must be taken care of.

Step 4: Run the program by clicking on the “Run” option.

VBA Datevalue Example 1-3.png

Or we can check or debug the program step-by-step, selecting the “Step Into” option under the “Debug” menu. If our code is without any errors, it displays the output.

VBA Datevalue Example 1-4

Step 5: When we execute the program, it first displays the message box with the date given in the text input. Next, click on “OK” to see the year value again, and click “OK” on the message box to see the month value.

VBA Datevalue Example 1-5

Note: One must follow these steps clearly to have accurate results.

Example #2 – Using the DatePart to Get the Different Parts of Date

Step 1: Go to the Excel Developer TabEnabling the developer tab in excel can help the user perform various functions for VBA, Macros and Add-ins like importing and exporting XML, designing forms, etc. This tab is disabled by default on excel; thus, the user needs to enable it first from the options menu.read more, place the cursor on a cell in the Excel sheet, click on the “Insert” option, and choose “Command Button” under “ActiveX Control,” as shown in the figure.

Datepart Example 2

Step 2: Drag the button and give the caption “DatePart” under “Properties.”

datepart Example 2-1

Double click on this button. It directs to the Visual Basic Editor sheet and displays as follows.

Step 3: Develop the code using the DatePart with DateValue, as shown in the figure.

Code:

Private Sub Datepart1_Click()

 Dim partdate As Variant
 partdate = DateValue("8/15/1991")
 MsgBox partdate
 MsgBox Datepart("yyyy", partdate)
 MsgBox Datepart("dd", partdate)
 MsgBox Datepart("mm", partdate)
 MsgBox Datepart("q", partdate)

End Sub

Example 2-2

In this program, DatePart1 is the macro name, and partdate is the argument name with data type ‘variant.’ For displaying year, date, month, and a quarter, one must apply the format as “yyyy,” “d,” “m,” and “q.” If we make any mistake in the format, it displays the following error.

Example 2-3

Step 4: After successfully debugging the program, run the program by clicking on the “Run” button to use excel shortcut keyAn Excel shortcut is a technique of performing a manual task in a quicker way.read more F5.

The code first displays the full date. Then, after clicking every “OK” from the msgbox, it shows the year value after that, DateValue, Month Value, Quater Value, respectively.

VBA Datevalue Example 2-4

Things to Remember About the VBA DATEVALUE

One must remember the following things while using the DateValue function in Excel VBA:

  • Run time error 13 with the message “Type Mismatch” is displayed when the date provided to the DateValue function cannot convert into a valid date. We need the date in a proper text format.
  • When we try to get the only date from the string argument with code ‘msgbox date (argument name),’ it displays the type mismatch error.
  • We can see the output of the DateValue function without opening the VBA editor. It is done by clicking the “Command” button and selecting the macro created for the respective program.
  • When DatePart is used to get the values, we should follow the appropriate format. Otherwise, it leads to ‘run time error 5’ with a message invalid procedure call or argument.

Recommended Articles

This article has been a guide to VBA DateValue. Here, we will learn how to use the VBA DateValue function to return the serial number or value of the date provided in the string, along with practical examples and a downloadable template. Below you can find some useful Excel VBA articles: –

  • VBA Save As
  • VBA DatePart
  • Use DateDiff Function in VBA
  • VBA DateAdd

Return to VBA Code Examples

DateValue Description

Returns the serial number of a date.

Simple DateValue Examples

Here is a simple DateValue example:

Sub DateValue_Example()
    MsgBox DateValue("Feb 12, 2019")
End Sub

This code will return 02/12/2019.

Following examples will have same result.

DateValue("2 12 2019")
DateValue("2/12/2019")
DateValue("2,12,2019")
DateValue("2-12-2019")
DateValue("February 12, 2019")
DateValue("Feb/12/2019")
...

If date is a string that includes only numbers separated by valid date seperators(” “, “/”, “,”, “-“), DateValue recognizes the order for month, day, and year according to the Short Date format that you specified for your system. DateValue also recognizes unambiguous dates that contain month names, either in long or abbreviated form.

If the year part of date is omitted, DateValue uses the current year from your computer’s system date.

If the date argument includes time information, DateValue doesn’t return it. However, if date includes invalid time information (such as “37:69”), an error occurs.

DateValueAdd Syntax

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

The DateAdd function contains an argument:

Date: A string of text representing a date (ex. “January 1, 2021”)

Examples of Excel VBA DateValue Function

You can reference a cell containing a date:

Sub DateValue_ReferenceDates_Cell()
    
    MsgBox DateValue(Range("C2").Value)
    
End Sub

This will return 01/02/2019.

The DateValue recognizes the month, day, and year for a valid date string.

DateValue("6-15-2019")
DateValue("15-6-2019")

Result: 06/15/2019

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!
vba save as

Learn More!

totn Excel Functions


This Excel tutorial explains how to use the Excel DATEVALUE function with syntax and examples.

Description

The Microsoft Excel DATEVALUE function returns the serial number of a date.

The DATEVALUE function is a built-in function in Excel that is categorized as a Date/Time Function. It can be used as a worksheet function (WS) and a VBA function (VBA) in Excel. As a worksheet function, the DATEVALUE function can be entered as part of a formula in a cell of a worksheet. As a VBA function, you can use this function in macro code that is entered through the Microsoft Visual Basic Editor.

Syntax

The syntax for the DATEVALUE function in Microsoft Excel is:

DATEVALUE( date )

Parameters or Arguments

date
A string representation of a date.

Returns

The DATEVALUE function returns a date value when used as a VBA function and it returns a serial date when used as a worksheet function. A serial date is how Excel stores dates internally and it represents the number of days since January 1, 1900.

Applies To

  • Excel for Office 365, Excel 2019, Excel 2016, Excel 2013, Excel 2011 for Mac, Excel 2010, Excel 2007, Excel 2003, Excel XP, Excel 2000

Type of Function

  • Worksheet function (WS)
  • VBA function (VBA)

Example (as Worksheet Function)

Let’s look at some Excel DATEVALUE function examples and explore how to use the DATEVALUE function as a worksheet function in Microsoft Excel:

Microsoft Excel

Based on the Excel spreadsheet above, the following DATEVALUE examples would return:

=DateValue(A1)
Result: 41153

=DateValue(A2)
Result: 41152

=DateValue(A3)
Result: 41501

=DateValue("30-Nov-2012")
Result: 41243

Example (as VBA Function)

The DATEVALUE function can be used in VBA code in Microsoft Excel.

Let’s look at some Excel DATEVALUE function examples and explore how to use the DATEVALUE function in Excel VBA code:

Dim LDate As Date

LDate = DateValue("May 15, 2012")

In this example, the variable called LDate would now contain the value of 5/15/2012.

VBA DateValue Function in Excel is a built-in function in MS Excel. It has one input argument or parameter. VBA DateValue Function returns the date value representing date for a string. It is a ‘Data and Time’ type function. It can be used in either procedure or function in a VBA editor window in Excel. We can use the VBA DateValue Function any number of times in any number of procedures or functions. In the following section we learn what is the syntax and parameters of the DateValue function.We will also see where we can use this VBA DateValue Function and real-time examples.

Table of Contents:

  • Objective
  • Syntax of VBA DateValue Function
  • Parameters or Arguments
  • Where we can apply or use the VBA DateValue Function?
  • Example 1: Convert the given input string to a valid date and display on the screen
  • Example 2: Convert the given input string to a valid date and display on the Worksheet
  • Download File
  • Instructions to Run VBA Macro Code
  • Other Useful Resources

The syntax of the VBA DateValue Function is

DATEVALUE(date_value)

Parameters or Arguments

There is one parameter or argument for the DateValue Function in VBA. That is nothing but ‘date_value’ parameter. It is a mandatory argument. It represents date in string format.

Where we can apply or use the VBA DateValue Function?

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

Example 1: Convert the given input string to a valid date and display on the screen

Here is a simple example of the VBA DateValue Function. This below example macro uses the DateValue Function and displays date for the specified string. In this case specified string represents date.

Sub VBA_DATEVALUE_Function_Example1()
'Convert the given input string to a valid date and display on the screen
    
    'Variable declaration
    Dim dDate As Date
    
    'Assign date to a variable
    dDate = DateValue("May 20, 2017")
    
    'Display output on the screen
    MsgBox "Specified Date is: " & dDate, vbInformation, "VBA DATEVALUE Function"
    
End Sub 

In the above example ‘dDate declared as ‘Date’ data type. And DATEVALUE is a vba function. This variable ‘dDate’ now contains the date.
Output:Here is the screen shot of first example output.
VBA DATEVALUE Function Example 1

Example 2: Convert the given input string to a valid time and display on the Worksheet

Here is another example of the VBA DateValue Function. This below example macro uses the DateValue Function and displays date for the specified string(date). Now, it displays on the Worksheet named ‘VBAF1.Com’ at Range ‘B20’.

Sub VBA_DATEVALUE_Function_Example2()
'Convert the given input string to a valid date and display on the Worksheet
    
    'Variable declaration
    Dim dDate As Date
    
    'Assign date to a variable
    dDate = DateValue("May 20, 2017")
    
    'Display output on the screen
    Sheets("VBAF1.COM").Range("B20") = "Specified Date is: " & dDate
    
End Sub 

Output: Here is the screen shot of second example output.
VBA DATEVALUE Function Example 2

Download File:

Click on following link to download free example excel workbook to learn more about the DateValue Function.

VBA DateValue Function Examples

Instructions to Run VBA Macro Code or Procedure:

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

Instructions to run VBA Macro Code

Other Useful Resources:

Click on the following links of the useful resources. These helps to learn and gain more knowledge.

VBA Tutorial VBA Functions List VBA Arrays in Excel Blog

VBA Editor Keyboard Shortcut Keys List VBA Interview Questions & Answers

Home / VBA / Top VBA Functions / VBA DATEVALUE Function (Syntax + Example)

The VBA DATEVALUE function is listed under the date category of VBA functions. When you use it in a VBA code, it can return a date from a text representing a date. In simple words, it can convert a date into an actual date which is stored as text. If there is a time with that date it will ignore it. It’s just like the DATEVALUE function in the worksheet.

DateValue(Date)

Arguments

  • Date: A string that represents a valid date as per VBA.

Example

To practically understand how to use the VBA DATEVALUE function, you need to go through the below example where we have written a vba code by using it:

Sub example_DATEVALUE()
Range("B1").Value = DateValue(Range("A1"))
End Sub

In the above example, we have used the DATEVALUE to convert a date stored as text in cell A1 and it has converted that data into an actual date in cell B1.

Notes

  • If the value specified is a value other than a date or a date that can’t be recognized as a date, VBA will return the run-time 13 error.
  • And if the date is NULL, it will return NULL.

Понравилась статья? Поделить с друзьями:
  • Datevalue excel на русском
  • Datetime in vba excel
  • Datetime from string excel
  • Dates as text in excel
  • Dates and times in excel vba