Функция time vba excel

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

Функция Date

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

Синтаксис

Пример

Sub PrimerDate()

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

End Sub

Функция DateAdd

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

Синтаксис

DateAdd(interval, number, date)

Параметры

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

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

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

Пример

Sub PrimerDateAdd()

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

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

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

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

End Sub

Функция DateDiff

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

Синтаксис

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

Параметры

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

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

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

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

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

Пример

Sub PrimerDateDiff()

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

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

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

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

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

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

End Sub

Функция DatePart

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

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

Синтаксис

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

Параметры

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

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

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

Пример

Sub PrimerDatePart()

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

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

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

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

End Sub

Функция DateSerial

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

Синтаксис

DateSerial(year, month, day)

Параметры

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

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

Пример

Sub PrimerDateSerial()

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

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

End Sub

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

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

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

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

Функция DateValue

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

Синтаксис

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

Пример

Sub PrimerDateValue()

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

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

End Sub

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

Функция Day

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

Синтаксис

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

Пример

Sub PrimerDay()

    MsgBox Day(Now)

End Sub

Функция IsDate

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

Синтаксис

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

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

Пример

Sub PrimerIsDate()

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

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

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

End Sub

Функция Hour

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

Синтаксис

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

Пример

Sub PrimerHour()

    MsgBox Hour(Now)

    MsgBox Hour(«22:36:54»)

End Sub

Функция Minute

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

Синтаксис

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

Пример

Sub PrimerMinute()

    MsgBox Minute(Now)

    MsgBox Minute(«22:36:54»)

End Sub

Функция Month

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

Синтаксис

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

Пример

Sub PrimerMonth()

    MsgBox Month(Now)

End Sub

Функция MonthName

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

Синтаксис

MonthName(month, [abbreviate])

Параметры

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

Пример

Sub PrimerMonthName()

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

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

End Sub

Функция Now

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

Синтаксис

Пример

Sub PrimerNow()

    MsgBox Now

    MsgBox Day(Now)

    MsgBox Hour(Now)

End Sub

Функция Second

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

Синтаксис

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

Пример

Sub PrimerSecond()

    MsgBox Second(Now)

    MsgBox Second(«22:30:14»)

End Sub

Функция Time

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

Синтаксис

Пример

Sub PrimerTime()

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

End Sub

Функция TimeSerial

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

Синтаксис

TimeSerial(hour, minute, second)

Параметры

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

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

Пример

Sub PrimerTime()

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

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

End Sub

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

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

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

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

Функция TimeValue

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

Синтаксис

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

Пример

Sub PrimerTimeValue()

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

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

End Sub

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

Функция Weekday

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

Синтаксис

Weekday(date, [firstdayofweek])

Параметры

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

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

Пример

Sub PrimerWeekday()

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

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

End Sub

Функция WeekdayName

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

Синтаксис

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

Параметры

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

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

Пример

Sub PrimerWeekdayName()

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

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

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

End Sub

Функция Year

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

Синтаксис

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

Пример

Sub PrimerYear()

    MsgBox Year(Now)

End Sub

Приложение 1

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

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

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

Приложение 2

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

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

Приложение 3

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

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

VBA Time

Excel VBA Time

VBA TIME function returns the current time as output and can also be used as an input to different macro lines of code. This function does not have any parameter set for it and thus, by far has the simplest syntax as TIME word with empty parentheses which can be seen as below:

The syntax for VBA TIME function:

Time()

In fact, there is no need for parentheses as well, you can simply use the word TIME itself in your block of code which allows your system to return the current time. We also have a similar function called NOW() under Excel VBA which returns the current time along with the date. However, in this article, our entire focus would be on using TIME function and looking at different working examples of the same.

How to Use Excel VBA Time Function?

We will learn how to use a VBA Time function with few examples in excel.

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

VBA Time Function – Example #1

Current System Time Using TIME function:

Follow the below steps to display the current time of your system.

Step 1: Define a sub-procedure.

Code:

Sub TimeExample1()

End Sub

VBA Time Example 1-1

Step 2: Define a variable which will be useful to hold the value of time for you. Define it as String.

Code:

Sub TimeExample1()
Dim CurrentTime As String
End Sub

VBA Time Example 1-2

Note: The reason behind defining this variable as String is, the output of the TIME function is in a string.

Step 3: Use VBA TIME function to assign current time to the variable defined in the step above using an assignment operator.

Code:

Sub TimeExample1()
Dim CurrentTime As String
CurrentTime = Time
End Sub

VBA Time Example 1-3

Step 4: As I mentioned earlier, there is no need to add parentheses after TIME function as this is a volatile function. Having said that, the following code will give the equivalent output in comparison with the above code.

Code:

Sub TimeExample1()
Dim CurrentTime As String
CurrentTime = Time()
End Sub

VBA Time Example 1-4

Step 5: Now, use a MsgBox function to display the current time using the display message box.

Code:

Sub TimeExample1()
Dim CurrentTime As String
CurrentTime = Time()
MsgBox CurrentTime
End Sub

VBA Time Example 1-5

Step 6: Run this code by hitting F5 or Run button and see the output. You should get the output as shown in the image below.

Result of Example 1-6

Please note that the time reflecting in the image above is the time by which this code is run on the system. While trying it by yourself, your output may vary depending on the time you are working on this code.

VBA Time Function – Example #2

VBA TIME in combination with a Date function to return the current time with Today’s Date:

As it has been informed earlier in the introduction of this article, there is a function called NOW() which gives you current date as well as time in Microsoft Excel. See the screenshot given below.

VBA Time Example 2-1

However, in VBA we don’t have this function working. Therefore, in VBA we have to use a combination of VBA Date and VBA TIME functions to get the current date and current time. VBA Date will give a current date and VBA Time will give current time (which we already have seen in the 1st example).

Let’s see step by step how we can achieve this.

Step 1: Insert a new module in your Excel VBA script.

VBA Time Example 2-2

Step 2: Define a new sub-procedure by giving a name to the macro.

Code: 

Sub Example2()

End Sub

VBA Time Example 2-3

Step 3: We wanted our output to be stored in cell A1 of our excel sheet. For that, start writing the code as below.

Code: 

Sub Example2()
Range("A1").Value =
End Sub

VBA Time Example 2-4

Step 4: Now, use a combination of VBA DATE and VBA TIME functions as shown below and assign it’s value to cell A1.

Code:

Sub Example2()
Range("A1").Value = Date & " " & Time
End Sub

VBA Time Example 2-5

The DATE function will return the current date of system and TIME function will return the current time. The white space enclosed in double quotes (“ “) allows having a space between date and time in the final output. Two & (and) operators work as concatenating operators which concatenate DATE and TIME with space in it.

Step 5: Run the code by hitting F5 or Run button manually. You will see the output in cell A1 of your worksheet as blow:

VBA Time Example 2-6

Here, again please note that the time reflecting in cell A1 is date and time by which this code is being run by myself. Therefore, when you’ll run this code the outputs will be different.

We also can format the date and time values using NumberFormat function under VBA.

Step 6: Write the code mentioned below in your VBA script.

Code:

Sub Example2()
Range("A1").Value = Date & " " & Time
Range("A1").NumberFormat = "dd-mmm-yyyy hh:mm:ss AM/PM"
End Sub

VBA Time Example 2-7

Step 7: Hit F5 or Run button manually and you’ll see the output as below in cell A1 of your worksheet.

Result of Example 2-8

VBA Time Function – Example #3

VBA TIME function to track the opening time and date of a workbook:

Sometimes, there is one spreadsheet which we open frequently (Like Employee list of an organization) and make changes into it. We might be interested in knowing the date and time on which the changes have been made in the worksheet. VBA Time function can be used to track the date and time every time a workbook is opened. See the steps below to work on the same.

Step 1: Create a new worksheet in your Excel workbook and rename it as per your convenience. I will rename it as (Time_Track).

Example 3-1

Step 2: Double click on ThisWorkbook under VBE (Visual Basics Editor).

This Workbook

Step 3: From object drop-down list select Workbook instead of General.

Workbook

Step 4: You’ll see a new private sub-procedure will get defined under the name Workbook_Open() in VBE.

Code:

Private Sub Workbook_Open()

End Sub

VBA Time Example 3-4

Step 5: Write down the below-mentioned code in this macro sub-procedure as shown in the image below:

Code:

Private Sub Workbook_Open()
Dim LB As Long
LB = Sheets("Time_Track").Cells(Rows.Count, 1).End(xlUp).Row + 1
Sheets("Time_Track").Cells(LB, 1).Value = Date & " " & Time()
End Sub

VBA Time Example 3-5

Here a variable LB of type Long is defined to find out the cell next to last used cell where the output can be stored. Then, using a combination of VBA DATE and TIME functions, we have assigned a value under that cell.

Step 6: Run the code by hitting F5 or Run button manually and see the output under column A of a worksheet.

Result of Example 3-6

This code will store the value of Date and Time every time you open the worksheet Time_Track.

This is it from this article. Let’s wrap the things up by writing some things to remember.

Things to Remember

  • VBA TIME function stores output as a string in excel. However, we also can store it as Date format while defining a variable as Date instead of a string.
  • TIME function does not require any argument in it. It’s a volatile function.
  • Even it does not need parentheses to call the function. Only TIME is enough to get the current time.
  • TIME function by default stores time value in hh:mm:ss format (24 hours clock format). However, sometimes the output format depends on your system time format as well.

Recommended Articles

This has been a guide to VBA Time Function. Here we have discussed how to use Excel VBA Time Functions and also we learned the Combination of date and time as an alternative to Now() Function and tracks the workbook open records along with some practical examples and downloadable excel template. You can also go through our other suggested articles –

  1. VBA MsgBox
  2. VBA Do While Loop
  3. VBA IsError
  4. VBA XML

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.

VBA Time function returns the current time. Also, the important thing to note is that this function has no arguments whatsoever. Another important factor is that this function returns the current system time. Using this function, we can find the time taken by the line of codes to complete the process.

TIME is a kind of volatile function. It does not have any syntax to it.

We also have a similar function in Excel – NOW () functionIn an excel worksheet, the NOW function is used to display the current system date and time. The syntax for using this function is quite simple =NOW ().read more, which inserts both current times and the current date in the spreadsheet.

TIME ()

We need to enter the function. No need for parenthesis to enclose. Just the TIME function is enough to insert the current time. The result given by the TIME function is in the String.

Table of contents
  • Excel VBA Time Function
    • How to Use TIME Function in VBA?
    • Alternative of Now() Function
    • Track Your Workbook Open Records using Time Function in VBA
    • Recommended Articles

VBA Time Function

You are free to use this image on your website, templates, etc, Please provide us with an attribution linkArticle Link to be Hyperlinked
For eg:
Source: VBA Time Function (wallstreetmojo.com)

How to Use TIME Function in VBA?

Let me show you an example of a simple TIME in excelTime is a time worksheet function in Excel that is used to calculate time based on the inputs provided by the user. The arguments can take the following formats: hours, minutes, and seconds.read more function. Then, follow the below steps to create code to use the TIME function.

You can download this VBA Time Function Template here – VBA Time Function Template

Step 1: Create a Macro.

Code:

Sub Time_Example1()
End Sub

VBA Time Example 1

Step 2: Declare a variable as String.

Code:

Sub Time_Example1()

  Dim CurrentTime As String

End Sub

VBA Time Example 1-1

Step 3: Assign a value to this variable through the TIME function.

Code:

Sub Time_Example1()

  Dim CurrentTime As String

  CurrentTime = Time

End Sub

Visual Basic Application Example 1-2

Step 4: Now, show the result in the message box.

Code:

Sub Time_Example1()

  Dim CurrentTime As String

  CurrentTime = Time

  MsgBox CurrentTime

End Sub

Visual Basic Application Example 1-3

Run this code using the F5 key or manually. We will get the current time.

Visual Basic Application Example 1-4

So, when we ran this code, the time was 11.51.54 AM.

Alternative of Now() Function

Combination of Date & Time as an Alternative to NOW Function

As we said at the beginning of the article, the NOW function can insert the current date and time. However, we can use two other functions as an alternative to the NOW function. Those two functions are VBA DATEVBA Date is a date and time function. It returns only the current date as per the system date you are using and has no arguments whatsoever. This function returns the current system date.read more & VBA TIME functions.

VBA Date will return the current date, and the Time function will return the current time, making the NOW function. Below is a set of codes that will insert the current date and time in cell A1.

Code:

Sub Time_Example2()

  Range("A1").Value = Date & " " & Time

End Sub

VBA Time Example 2

This code will insert the current date and time in cell A1.

VBA Time Example 2-1

We can also apply a format to these values using the FORMAT function. For example, the below code will format the date and time.

Code:

Sub Time_Example2()

  Range("A1").Value = Date & " " & Time

  Range("A1").NumberFormat = "dd-mmm-yyyy hh:mm:ss AM/PM"

End Sub

VBA Time Example 2-2

Now, the result of this code is as follows.

VBA Time Example 2-2

Track Your Workbook Open Records using Time Function in VBA

Often, we need to know our workbook opening time frequency. For example, there is a situation where we open the workbook quite often, and we make some changes. Then, we can track the workbook opening time and date by tracking the workbook opening time.

Create a new sheet and rename it “Track Sheet.”

VBA Time Example 3

Step 1: Double-click on ThisWorkbook from VBE Editor.

Visual Basic Application Time Example 3-1

Step 2: Select the workbook from the object drop-down list.

Visual Basic Application Time Example 3-2

Step 3: As soon as you select this option, you can see a new Macro automatically created by itself in the name “Workbook_Open().”

VBA Time Example 3-3

Step 4: Inside this Macro, we will need to write a code to track the workbook opening date and time.

We have already written the code. Below is the code for you.

Code:

Private Sub  Workbook_Open()

Dim LR As Long

LR = Sheets("Track Sheet").Cells(Rows.Count, 1).End(xlUp).Row + 1

Sheets("Track Sheet").Cells(LR, 1).Value = Date & " " & Time()
Sheets("Track Sheet").Cells(LR, 1).NumberFormat = "dd-mmm-yyyy hh:mm:ss AM/PM"

End Sub

Visual Basic Application Example 3-4

It will record your workbook opening times like the below one.

Visual Basic Application Example 3-5

Recommended Articles

This article has been a guide to VBA Time Function. Here, we learned how to use the VBA Time function and the combination of date and time as an alternative to the NOW() function and track the open workbook records along with examples and a downloadable Excel sheet. Below are some useful Excel articles related to VBA: –

  • VBA Paste Method
  • Time Card Template
  • Excel Convert Function
  • CDATE Function in VBA

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

The VBA TIME function is listed under the time category of VBA functions. When you use it in a VBA code, it returns the current time in the result. This current time will be according to the system’s current time.

Time()

Arguments

  • There’s no argument to specify in this function.

Example

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

Sub example_TIME()
Range("A1").Value = Time()    
End Sub

In the above code, we have used TIME to get the current time in cell A1.

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

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

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

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

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

  • Excel VBA Time

Excel VBA Time

Функция VBA TIME возвращает текущее время в качестве выходных данных и может также использоваться в качестве входных данных для различных макросовых строк кода. Эта функция не имеет никакого набора параметров для нее и, таким образом, на сегодняшний день имеет самый простой синтаксис, как слово TIME с пустыми скобками, которое можно увидеть, как показано ниже:

Синтаксис для функции VBA TIME:

Время()

На самом деле в скобках также нет необходимости, вы можете просто использовать само слово TIME в своем блоке кода, что позволяет вашей системе возвращать текущее время. У нас также есть аналогичная функция NOW () в Excel VBA, которая возвращает текущее время вместе с датой. Однако в этой статье все наше внимание будет сосредоточено на использовании функции TIME и рассмотрении различных рабочих примеров одного и того же.

Как использовать функцию времени VBA Excel?

Мы узнаем, как использовать функцию VBA Time, с несколькими примерами в Excel.

Вы можете скачать этот шаблон VBA Time Excel здесь — Шаблон VBA Time Excel

Функция времени VBA — Пример # 1

Текущее системное время с использованием функции TIME:

Выполните следующие шаги, чтобы отобразить текущее время вашей системы.

Шаг 1: Определите подпроцедуру.

Код:

 Sub TimeExample1 () End Sub 

Шаг 2: Определите переменную, которая будет полезна для хранения значения времени для вас. Определите это как строку.

Код:

 Sub TimeExample1 () Dim CurrentTime As String End Sub 

Примечание . Причина определения этой переменной как String заключается в том, что выходные данные функции TIME находятся в строке.

Шаг 3: Используйте функцию VBA TIME, чтобы назначить текущее время переменной, определенной на шаге выше, с помощью оператора присваивания.

Код:

 Sub TimeExample1 () Dim CurrentTime As String CurrentTime = Время окончания Sub 

Шаг 4: Как я упоминал ранее, нет необходимости добавлять скобки после функции TIME, так как это изменчивая функция. Сказав это, следующий код даст эквивалентный вывод по сравнению с приведенным выше кодом.

Код:

 Sub TimeExample1 () Dim CurrentTime As String CurrentTime = Time () End Sub 

Шаг 5: Теперь используйте функцию MsgBox, чтобы отобразить текущее время с помощью окна сообщений на дисплее.

Код:

 Sub TimeExample1 () Dim CurrentTime As String CurrentTime = Time () MsgBox CurrentTime End Sub 

Шаг 6: Запустите этот код, нажав F5 или кнопку Run, и посмотрите результат. Вы должны получить вывод, как показано на рисунке ниже.

Обратите внимание, что время, отраженное на изображении выше, является временем, в течение которого этот код запускается в системе. При самостоятельной попытке ваш вывод может отличаться в зависимости от времени работы с этим кодом.

Функция времени VBA — пример № 2

VBA TIME в сочетании с функцией Date для возврата текущего времени с Today’s Date:

Как было сообщено ранее во введении к этой статье, есть функция NOW (), которая отображает текущую дату и время в Microsoft Excel. Смотрите скриншот, приведенный ниже.

Однако в VBA эта функция не работает. Поэтому в VBA мы должны использовать комбинацию функций VBA Date и VBA TIME, чтобы получить текущую дату и текущее время. VBA Date даст текущую дату, а VBA Time даст текущее время (которое мы уже видели в первом примере).

Давайте посмотрим шаг за шагом, как мы можем достичь этого.

Шаг 1: Вставьте новый модуль в ваш скрипт VBA для Excel.

Шаг 2: Определите новую подпроцедуру, дав имя макросу.

Код:

 Sub Example2 () End Sub 

Шаг 3: Мы хотели, чтобы наш вывод был сохранен в ячейке A1 нашего листа Excel. Для этого начните писать код, как показано ниже.

Код:

 Sub Example2 () Диапазон ("A1"). Значение = Конец Sub 

Шаг 4. Теперь используйте комбинацию функций VBA DATE и VBA TIME, как показано ниже, и присвойте это значение ячейке A1.

Код:

 Sub Example2 () Диапазон ("A1"). Значение = Дата & "" & Sub End Sub 

Функция DATE возвращает текущую дату системы, а функция TIME возвращает текущее время. Пробел, заключенный в двойные кавычки («»), позволяет использовать пробел между датой и временем в конечном выводе Два оператора & (и) работают как объединяющие операторы, которые объединяют DATE и TIME с пробелом в нем.

Шаг 5: Запустите код, нажав F5 или кнопку Run вручную. Вы увидите результат в ячейке A1 вашего листа как удар:

Здесь, опять же, обратите внимание, что время, отображаемое в ячейке A1, — это дата и время, когда этот код выполняется мной самостоятельно. Поэтому, когда вы запустите этот код, результаты будут другими.

Мы также можем отформатировать значения даты и времени, используя функцию NumberFormat в VBA.

Шаг 6: Напишите код, указанный ниже, в вашем VBA-скрипте.

Код:

 Sub Example2 () Range ("A1"). Значение = Дата & "" & Диапазон времени ("A1"). NumberFormat = "дд-ммм-гггг чч: мм: сс AM / PM" End Sub 

Шаг 7: Нажмите F5 или кнопку Run вручную, и вы увидите результат, как показано ниже, в ячейке A1 вашего рабочего листа.

Функция времени VBA — Пример № 3

Функция VBA TIME для отслеживания времени открытия и даты рабочей книги:

Иногда есть одна электронная таблица, которую мы часто открываем (например, список сотрудников организации) и вносим в нее изменения. Возможно, нам будет интересно узнать дату и время внесения изменений в таблицу. Функция времени VBA может использоваться для отслеживания даты и времени при каждом открытии рабочей книги. Смотрите шаги ниже, чтобы работать над тем же.

Шаг 1. Создайте новый лист в вашей книге Excel и переименуйте его, как вам удобно. Я переименую его в (Time_Track).

Шаг 2: Дважды щелкните ThisWorkbook в VBE (редактор Visual Basics).

Шаг 3. В раскрывающемся списке объектов выберите «Рабочая книга» вместо «Общие».

Шаг 4: Вы увидите, что новая частная подпроцедура будет определена под именем Workbook_Open () в VBE.

Код:

 Private Sub Workbook_Open () End Sub 

Шаг 5: Запишите нижеупомянутый код в этой подпроцедуре макроса, как показано на рисунке ниже:

Код:

 Private Sub Workbook_Open () Dim LB As Long LB = Sheets ("Time_Track"). Ячейки (Rows.Count, 1) .End (xlUp) .Row + 1 Sheets ("Time_Track"). Ячейки (LB, 1). Значение = Дата & "" & Время () End Sub 

Здесь определяется переменная LB типа Long, чтобы определить ячейку рядом с последней использованной ячейкой, в которой можно сохранить выходные данные. Затем, используя комбинацию функций VBA DATE и TIME, мы присвоили значение этой ячейке.

Шаг 6: Запустите код, нажав F5 или кнопку Run вручную, и просмотрите результат в столбце A рабочего листа.

Этот код будет хранить значение даты и времени каждый раз, когда вы открываете рабочий лист Time_Track.

Это из этой статьи. Давайте подведем итоги, написав несколько вещей, которые нужно запомнить.

То, что нужно запомнить

  • Функция VBA TIME сохраняет вывод в виде строки в Excel. Тем не менее, мы также можем сохранить его как формат даты, определяя переменную как дату вместо строки.
  • Функция TIME не требует никаких аргументов. Это изменчивая функция.
  • Даже для вызова функции не нужны скобки. Только ВРЕМЯ достаточно, чтобы получить текущее время.
  • Функция TIME по умолчанию сохраняет значение времени в формате чч: мм: сс (24-часовой формат). Однако иногда формат вывода зависит также от формата вашего системного времени.

Рекомендуемые статьи

Это было руководство к функции времени VBA. Здесь мы обсудили, как использовать функции времени VBA в Excel, а также изучили сочетание даты и времени в качестве альтернативы функции Now () и отслеживают открытые записи рабочей книги вместе с некоторыми практическими примерами и загружаемым шаблоном Excel. Вы также можете просмотреть наши другие предлагаемые статьи —

  1. Как создать Excel VBA MsgBox?
  2. РАБОЧИЙ ДЕНЬ Excel Функция | формула
  3. Руководство по VBA Do While Loop
  4. Вставить дату в Excel

Понравилась статья? Поделить с друзьями:
  • Функция right в excel на русском
  • Функция textjoin в excel на русском
  • Функция rgb в excel
  • Функция text to column в excel
  • Функция rept в excel на русском