Excel vba time to value

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

TimeValue in VBA is an inbuilt function, also categorized under the Date and Time function in VBA. As the name suggests, this function gives us the numerical value of the date provided as an argument. It takes a single argument, the date, and returns the numerical value from the argument.

Table of contents
  • What Does Time Value Function Do in VBA?
    • Syntax of VBA TimeValue Function
    • Examples of TimeValue Function with Excel VBA
      • VBA TimeValue Example #2
      • VBA TimeValue Example #3
    • Recommended Articles

What Does Time Value Function Do in VBA?

The TimeValue function in VBA Excel returns the time value portion from the full date and time. It stores the date and time as serial numbers in Excel. Moreover, the serial number represents the DATE. The decimal represents the time. Therefore, using the TimeValue function, we can get only the time serial number, i.e., decimal number.

Syntax of VBA TimeValue Function

The syntax of the VBA TimeValue function is as follows.

VBA Timevalue Syntax

The TimeValue function returns the serial number part of the given date and stores it as a text value. Time is nothing but the actual time we are looking to get the serial number. Remember, the TimeValue function can only get the serial number from the time, which is stored as text, not as TIME.

Examples of TimeValue Function with Excel VBA

Below are examples of the VBA TimeValue function.

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

VBA TimeValue Example #1

Now, look at the simple example of the VBA TimeValue function.

Code:

Sub TIMEVALUE_Function_Example1()
'Convert the given input string to a valid time and display on the screen

'Variable declaration
Dim MyTime As Date

'Assign time to a variable
MyTime = TimeValue("28-05-2019 16:50:45")

'Display output on the screen
MsgBox "Current Time is: " & MyTime, vbInformation, "VBA TIMEVALUE Function"

End Sub

VBA TimeValue Example 1

First, we have declared the variable “MyTime” as a date.

Dim MyTime As Date

Then, we assign the value to the variable by applying TimeValue.

MyTime = TimeValue("28-05-2019 16:50:45")

Then in the message box, we have assigned the variable result.

MsgBox "Supplied Time is: " & MyTime, vbInformation, "TIMEVALUE Function".

If we run the code using the F5 key or manually, we will get the result as follows.

VBA TimeValue Example 1-1

VBA TimeValue Example #2

We will declare the VBA variable as “Double” for the same code.

Code:

Sub TIMEVALUE_Function_Example1()
'Convert the given input string to a valid time and display on the screen

'Variable declaration
Dim MyTime As Double

'Assign time to a variable
MyTime = TimeValue("28-05-2019 16:50:45")

'Display output on the screen
MsgBox "Current Time is: " & MyTime, vbInformation, "VBA TIMEVALUE Function"

End Sub

VBA TimeValue Example 2-1

Now, if we run the VBA codeVBA code refers to a set of instructions written by the user in the Visual Basic Applications programming language on a Visual Basic Editor (VBE) to perform a specific task.read more manually or by pressing the F5 key, it will display the serial number part of the time, 16:50:45.

VBA TimeValue Example 2

For your better understanding, we will first enter the numbers given by the VBA message boxVBA MsgBox function is an output function which displays the generalized message provided by the developer. This statement has no arguments and the personalized messages in this function are written under the double quotes while for the values the variable reference is provided.read more to one of the cells.

Example 2-2

Now, we will apply the time format to check the exact result.

Example 2-3

You can see when you convert it into a time format.

VBA TimeValue Example 2-4

VBA TimeValue Example #3

Now, look at the below data.

Example 3

We have data and time together from A1 to A14 cells. For the second column, we need to extract only the time value. Since we have more than one cell to deal with, we need to employ loops to perform the same tasks for all the cells.

We have data from the 1st cell to the 14th cell, so our loop should run 14 times. We need to use FOR NEXT loop in VBAAll programming languages make use of the VBA For Next loop. After the FOR statement, there is a criterion in this loop, and the code loops until the criteria are reached. read more to mention the lower and upper limits. The Below code is the already written code to extract the time value from the date and time combination.

Code:

Sub TimeValue_Example3()

    Dim k As Integer

    For k = 1 To 14
        Cells(k, 2).Value = TimeValue(Cells(k, 1).Value)
    Next k

End Sub

Example 3-1

When we run the code, we will get the values below.

VBA TimeValue Example 3-1

If you wish to see the time, then apply TIME format to it.

So, this is how the TIMEVALUE function works in VBA and Excel.

Recommended Articles

This article has been a guide to VBA TimeValue. Here, we learn how to use the VBA TimeValue function to return the serial number from the stored text value, with practical examples and a downloadable template. Below you can find some useful Excel VBA articles: –

  • VBA Hide using Columns Property
  • VBA Timer
  • Pause VBA Code
  • VBA Now

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.

Excel VBA Dates & Time, Format Function, User Defined Date, Number & String Formats

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

Contents:

Excel VBA Dates & Time

Format Function in VBA

Named Date/Time Formats

Named Numeric Formats

Characters used to create User-Defined Number Formats with the VBA Format Function

Characters used to create User-Defined Date & Time Formats with the VBA Format Function

Characters used to create User-Defined String Formats with the VBA Format Function

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

Excel VBA Dates & Time

Excel Dates Equate to Serial Numbers — Excel stores all dates as integers and all times as decimal fractions. Your System’s Locale settings determines display format for Numbers, Currency, Date & Time. With the VBA Format function you can create User-Defined Date & Time Formats, Number Formats & String Formats, besides using predefined Named Date/Time & Numeric Formats. The Format function formats and returns an expression (String value) as per the specified format. Your system-defined formats include the Short Date Format, Long Date Format, Short Time Format, Long Time Format, and the Number & Currency Formats, which are specified in your computer’s regional settings, which determine your default display formats.

Date Data Type in VBA: Date equates to a numeric value which is the count of number of days elapsed from a certain referenced date. Dates are stored as 64-bit (8-byte) Double Precision floating-point numbers.

Variable Data Type Storage Size Range or Type of Values it Stores
 Date 8-bytes Holds either the date or the time, or both. Values can range from January 1, 100 to December 31, 9999. After declaring the variable, you can assign a value to it. A date value must be entered between two # signs, viz.  
DateOfBirth = #2/15/1961#
TimeOfBirth = #10:05 AM#
MarriageDate = #2/19/94 17:30#

Enclosing a date within number signs (#) ensures that the date literal will actually remain the date value which you actually mean to refer or use in your code. Generally the locale in which your application might be running (ie. Code Locale), determines the actual meaning of date value you enter, for ex. if you mean July 02, 2010 in a locale using mm/dd/yyyy, entering 07/02/2010 will compile your code correctly but entering 07/02/2010 in a locale using dd/mm/yyyy format will erroneously interpret as February 07, 2010 in your code. Using number signs (#) ensures that the date literal remains independent of your computer’s date and time format settings. Date literal is the date format specified by the locale settings for your code (ie. Code Locale). #7/2/2010# is the date literal that represents July 02, 2010, where English-U.S. is the locale setting for your application.

System’s Locale settings vs. Code Locale: The System’s Locale settings is the locale of the user who runs your program — the User Locale determines which default settings a user wants for formatting Numbers, Currency, Time & Date (used as a reference for user output) and uses Control Panel settings provided by the operating system. System-defined Format is dependent on your System’s Locale settings. The code locale is always English/U.S. in Visual Basic, irrespective of the international version being used. Short Time format and Short Date format of the Code Locale are used to Display Date and Time in the development environment ie. VBE in Excel.

To ensure that the date is correctly interpreted in any System Locale, enter dates within number signs (#), in code, in the format #month/day/year#. Because only English/U.S. is allowed in Visual Basic as a programming locale, the date will be the same to a user wherever your application is run. See below example.

Example: System-defined format (format specified in your computer’s regional settings) — Short Date Format is «dd-mm-yy» (English/U.K.) — refer Image 1a

Sub DateLiteral_1()

‘system-defined format (format specified in your computer’s regional settings) — Short Date Format is «dd-mm-yy» (English/U.K.) — refer Image 1a

Dim MyDate As Variant, MyDate1 As Variant

‘short date format of your Code Locale is always English/U.S. in Visual Basic, which determines display of Date in VBE

MyDate = #7/5/2014#

‘below format will assume your system-defined format:

‘returns «Saturday, July 5, 2014«

ActiveCell.Offset(1, 0) = Format(MyDate, «dddd, mmmm d, yyyy«)

ActiveCell.Offset(1, 1) = «date within number signs (# #)«

‘returns «Wednesday, May 7, 2014«

ActiveCell.Offset(2, 0) = Format(MyDate1, «dddd, mmmm d, yyyy«)

ActiveCell.Offset(2, 1) = «date within double quotes«

End Sub

Example: System-defined format (format specified in your computer’s regional settings) — Short Date Format is «m/d/yyyy»  (English/U.S.) — refer Image 1b

Sub DateLiteral_2()

‘system-defined format (format specified in your computer’s regional settings) — Short Date Format is «m/d/yyyy»  (English/U.S.) — refer Image 1b

Dim MyDate As Variant, MyDate1 As Variant

‘short date format of your Code Locale is always English/U.S. in Visual Basic, which determines display of Date in VBE

MyDate = #7/5/2014#

‘below format will assume your system-defined format:

MyDate1 = «7/5/2014«

‘returns «Saturday, July 5, 2014«

ActiveCell.Offset(1, 0) = Format(MyDate, «dddd, mmmm d, yyyy«)

ActiveCell.Offset(1, 1) = «date within number signs (# #)«

‘returns «Saturday, July 5, 2014«

ActiveCell.Offset(2, 0) = Format(MyDate1, «dddd, mmmm d, yyyy«)

ActiveCell.Offset(2, 1) = «date within double quotes«

End Sub

Format specified in your computer’s regional settings — Short Date / Long Date Format can be set or changed by the individual user manually  from the Formats tab of the Region item in Control Panel in Windows 8. Refer Image 2.

Excel Dates Equate to Serial Numbers:

Excel stores all dates as integers and all times as decimal fractions. With this system, Excel can add, subtract, or compare dates and times just like any other numbers, and all dates are manipulated by using this system. In this system, the serial number 1 represents 1/1/1900 12:00:00 AM, the first supported day from when the Excel calendar starts. Bug in Excel: Excel erroneously treats 1900 as a leap year, which has presumably been done knowingly by Microsoft to provide compatibility with Lotus 1-2-3, and so actually the bug would have been in Lotus 123 (Excel’s predecessor).

In Excel, Dates equate to a «serial number» (which is a numeric value) that is the count of number of days elapsed from a certain referenced date. Dates are stored as 64-bit (8-byte) Double Precision floating-point numbers. The integer part (values to the left of decimal) is the number of days elapsed since January 1, 1900. For example, January 1, 1900 is stored as 1; January 2, 1900 is stored as 2; March 15, 2001 is stored as 36,965. The fractional part (values to the right of decimal) holds time information, and represents the time as a fraction of a whole day. For example, 12.00AM (midnight) is stored as 0; 6:00AM is stored as 0.25; 12.00PM (noon) is stored as 0.5; 6:00PM is stored as 0.75; 6:00:30PM is stored as 0.750347222. To check the «serial number» of a date and time simply format the cell as «General» or format to number — conversely type a number in Excel and formatting the cell to date format will display the equivalent date. The Date and Time of «10/3/1954  6:00:00 AM» has a serial number of 20000.25.

Note that where the 1900 date system is used by Excel for Windows, but Excel for Mac uses the 1904 date system so that typing the number 1 in Excel and formatting it in date format will display 1/2/1904 12:00:00 AM in Excel for Mac while Excel for Windows displays it as 1/1/1900 12:00:00 AM. In Mac, you can change to the 1900 date system by clearing the 1904 date system in the Calculation tab (in Preferences) whereas in Excel for Windows you can change to the 1904 date system — in Excel 2007 click the Microsoft Office Button image, click Excel Options, and then click the Advanced category and  in the ‘When calculating this workbook’ options select the ‘Use 1904 date system‘.

Format Function in VBA

The vba Format function formats and returns an expression (String value) as per the specified format. Syntax: Format(expression, format, firstdayofweek, firstweekofyear). It is necessary to specify the expression argument, which is any expression you wish to format. The other 3 arguments are optional to specify. The format argument specifies a named or user-defined format expression — (i) to format numbers (or dates/times), you will use predefined named numeric (or date/time) formats or create user-defined numeric (or date/time) formats; (ii) to format date and time serial numbers, you will use date/time formats or numeric formats; (iii) to format strings you will create user-defined string formats. You can also use constants to specify the first day of the week or the first week of the year in the arguments of firstdayofweek and firstweekofyear respectively.

Formatting a number by omitting the format argument will return a String representation of the number, similar to using the Str vba function, but a positive number thus formatted will not include a leading space for the sign of number in the returned string like when using the Str function. 

While using the Format Function for Date formatting, you must specify the expression argument appropriately in Gregorian or Hijri depending if your Calendar property setting is Gregorian or Hijri.

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

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

Named Date/Time Formats

Listed below are predefined named Date and Time formats. Your system setting determines the Date display.

Format Name Description
General Date Displays a date and/or time, ex. 8/14/12 6:28 PM. The integer part (values to the left of decimal) displays a date, ex. 8/14/12, the fractional part (values to the right of decimal) displays time, ex. 6:28 PM. Your system setting determines the Date display — you can display only a Date or only a Time or both Date & Time.
Long Date Long Date Format refers to your system-defined long date format ie. the long date format specified in your computer’s regional settings, for example, Thursday, July 31, 2014.
Medium Date Medium Date Format displays a date using the medium date format appropriate for the language version of your Excel application (host application).
Short Date Short Date Format refers to your system-defined short date format ie. the short date format specified in your computer’s regional settings, for example, 7/31/2014.
Long Time Long Time Format refers to your system-defined long time format ie. the long time format specified in your computer’s regional settings, and typically includes hours, minutes, seconds, for example, 19:35:40.
Medium Time Medium Time Format displays time in 12-hour format showing hours and minutes and the AM/PM designator viz. 7:48 AM.
Short Time Short Time Format displays a time using the 24-hour format, and typically uses hours & minutes, for example, 19:35.

System-defined Format is dependent on your System’s Locale settings:

System Locale controls the language used when displaying text in programs that do not support Unicode. Applications affected by this setting are only those that do not use Unicode as their default character-encoding mechanism and hence this setting is not applicable to applications that are already Unicode-encoded. The system locale is a unique setting for each system and the administrator has to change it manually wherein the computer is required to be restarted for the changes to take effect. System locale can be set from the Administrative tab of the Region item in Control Panel in Windows 8.

The User Locale determines which default settings a user wants for formatting Numbers, Currency, Time & Date. The user locale can be set or changed by the individual user manually  from the Formats tab of the Region item in Control Panel in Windows 8. Locale-aware applications use this value to display formatted data.

Your System’s Locale settings (User Locale) determines display format for Numbers, Currency, Time & Date by running your code whereas the short time format and short date format of your Code Locale (which is always English/U.S. in Visual Basic) determines display of Time & Date in the development environment.

Example: Using Predefined Named Date and Time formats — System Settings — English (United States)

Sub PredefinedNamedDateAndTimeFormats_1()
‘Using Predefined Named Date and Time formats.

‘Your system setting determines the Date and Time display for General Date, Long Date, Short Date & Long Time;
‘Medium Date format is per the language version of your host Excel application;
‘Short Time Format uses a 24-hour format, displays hours & minutes;

‘SYSTEM SETTINGS SPECIFIED IN THE COMPUTER’S REGIONAL SETTINGS — English (United States):
‘Long Time Format = h:mm:ss tt
‘Long Date Format = dddd, MMMM d, yyyy
‘Short Time Format = h:mm tt
‘Short Date Format = M/d/yyyy
‘M = month; m = minute
‘AM & PM Symbol = AM & PM

Dim MyDate As Variant, MyTime As Variant, SerialNo As Variant, str As Variant

SerialNo = «41851.87«

MyDate = #7/31/2014#

MyTime = #7:16:32 PM#

‘returns «7/31/2014 8:52:48 PM»

str = Format(SerialNo, «General Date«)

MsgBox str

‘returns «Thursday, July 31, 2014»

str = Format(MyDate, «Long Date«)

MsgBox str

‘returns «31-July-14»

str = Format(MyDate, «Medium Date«)

MsgBox str

‘returns «7/31/2014»

str = Format(MyDate, «Short Date«)

MsgBox str

‘returns «7:16:32 PM»

str = Format(MyTime, «Long Time«)

MsgBox str

‘returns «07:16 PM»

str = Format(MyTime, «Medium Time«)

MsgBox str

‘returns «19:16»

str = Format(MyTime, «Short Time«)

MsgBox str

End Sub

Example: Using Predefined Named Date and Time formats — System Settings — English (United Kingdom)

Sub PredefinedNamedDateAndTimeFormats_2()

‘Using Predefined Named Date and Time formats.

‘Your system setting determines the Date and Time display for General Date, Long Date, Short Date & Long Time;
‘Medium Date format is per the language version of your host Excel application;
‘Short Time Format uses a 24-hour format, displays hours & minutes;

‘SYSTEM SETTINGS SPECIFIED IN THE COMPUTER’S REGIONAL SETTINGS — English (United Kingdom):
‘Long Time Format = HH:mm:ss
‘Long Date Format = dd MMMM yyyy
‘Short Time Format = HH:mm
‘Short Date Format = dd/MM/yyyy
‘h/H = 12/24 hour

‘M = month; m = minute

Dim MyDate As Variant, MyTime As Variant, SerialNo As Variant, str As Variant

SerialNo = «41851.87«

MyDate = #7/31/2014#

MyTime = #7:16:32 PM#

‘returns «31/07/2014 20:52:48»

str = Format(SerialNo, «General Date«)

MsgBox str

‘returns «31 July 2014»

str = Format(MyDate, «Long Date«)

MsgBox str

‘returns «31-July-14»

str = Format(MyDate, «Medium Date«)

MsgBox str

‘returns «31/07/2014»

str = Format(MyDate, «Short Date«)

MsgBox str

‘returns «19:16:32»

str = Format(MyTime, «Long Time«)

MsgBox str

‘returns «07:16 PM»

str = Format(MyTime, «Medium Time«)

MsgBox str

‘returns «19:16»

str = Format(MyTime, «Short Time«)

MsgBox str

End Sub

Named Numeric Formats

Listed below are predefined numeric format names.

Format Name Description
General Number General format cells have no specific number format and do not display the thousand separator.
Currency Currency format is used for general monetary values and displays number with the thousand separator. It typically displays two digits to the right of the decimal point and the currency symbol, final display being based on your system’s locale settings.
Fixed Fixed format displays a minimum of one digit to the left and two digits to the right of the decimal point.
Standard Standard format displays the thousand separator and a minimum of one digit to the left and two digits to the right of the decimal point.
Percent Percent format multiplies the number by 100 and displays the result with a percent symbol (%) to its right, with two digits to the right of the decimal point.
Scientific Scientific format uses standard scientific notation (exponential format), providing two significant digits.
Yes/No If number is 0 this format displays No, otherwise it displays Yes.
True/False If number is 0 this format displays False, otherwise it displays True.
On/Off If number is 0 this format displays Off, otherwise it displays On.

Example: Using Predefined Named Numeric formats.

Sub NamedNumericFormats()
‘Using Predefined Named Numeric formats.

Dim str As Variant

‘returns «5678.9523»

str = Format(5678.9523, «General Number«)

MsgBox str

‘returns «$5,678.95»

str = Format(5678.9523, «Currency«)

MsgBox str

‘returns «5678.90»

str = Format(5678.9, «Fixed«)

MsgBox str

‘returns «5,678.95»

str = Format(5678.9523, «Standard«)

MsgBox str

‘returns «595.23%»

str = Format(5.9523, «Percent«)

MsgBox str

‘returns «5.68E+03»

str = Format(5678.9523, «Scientific«)

MsgBox str

‘returns «Yes»

str = Format(-5.95, «Yes/No«)

MsgBox str

‘returns «True»

str = Format(5.95, «True/False«)

MsgBox str

‘returns «Off»

str = Format(0, «On/Off«)

MsgBox str

End Sub

Characters used to create User-Defined Number Formats with the VBA Format Function

    Syntax for VBA Format Function: Format(expression,format)
Character Description Format  Argument Expression Argument Formatted Display
0 (zero) Digit placeholder. If the number has lesser number of digits than zeros in the format code, the insignificant zeros are displayed. This means that the minimum number of digits are determined by the position of zero at the extreme left before decimal and position of zero at extreme right after decimal, in the format code. 0.00 5.6 5.60
  If the number has more digits than zeros to the left of the decimal point in the format code, the extra digits are displayed. 00.00 5.6 05.60
  The number of zeros to the right of the decimal point in the format code, determine the round off digits. The «00» format code rounds off to the nearest digit preceding the decimal point. 0.0 5.6 5.6
    0 0.6 1
    00.00 456.789 456.79
    00 45.445 45
         
# (number character) Digit placeholder. This follows the same rules as 0 (zero), except that, if the number has lesser number of digits than «#» characters in the format code, the insignificant zeros are NOT displayed, even though it may be the only digit. ###.## 456.6 456.6
  If the number has more digits than # characters to the left of the decimal point in the format code, the extra digits are displayed. # 456.68 457
  The number of # to the right of the decimal point in the format code, determine the round off digits. The «##» format code rounds off to the nearest digit preceding the decimal point. (###) ### — #### 4567891234 (456) 789 — 1234
    ##.# 456.689 456.7
    ## 45.678 46
         
. (period) Decimal placeholder. The decimal point (ie. the «.» character) in the format code determines the decimal place. Some locales use comma as the decimal separator instead of period. 00.000 456.123456 456.123
  The number of Digit Placeholders to the right of the decimal point in the format code, determine the round off digits. For the first digit placeholder to the left of the decimal separator use 0 to display a leading zero with fractional numbers. 00.00 456.789567 456.79
  The «00» or «##» format codes round off to the nearest digit preceding the decimal point. ##.# 456.789567 456.8
    ##.# 0.65 7
         
% (percent sign) Percentage indicator. Numbers are displayed as a percentage of 100 with this. The percent sign in the format code multiplies the number by 100, before it is formatted. The symbol «%» is displayed at the same position at which it is inserted in the format code. #.0% 0.00625 .6%
    0.000% 0.00625 0.625%
    #.##% 0.00625 .63%
    %# 0.5625 %1
    #% 0.5625 56%
         
, (comma) Thousand separator and Number scaling. Some locales use period (.) as a thousand separator. # 123456 123456
  Thousand separator: In the format code, placing comma between two digit placeholders and to the left of decimal, will act as a thousand separator. #,### 123456 123,456
  Number Scaling: If comma is placed to the immediate left of the decimal point (in the format code), the number is divided by 1,000, n number of times wherein n is the number of characters «,». The format string «0,,» will scale down the number 100 million to 100 (divides 100 million by 1,000 * 1,000); and the format code «0,,,» will divide the number by 1,000 * 1,000 * 1,000. Note that this number scaling will not apply the thousand separator, which will have to be done separately after the number scaling. A comma in any position other than to the immediate left of the decimal point will only act as a thousand separator. #,#00 123456 123,456
    #,###.## 4567.234 4,567.23
    0, 10000 10
    #,##0,, 1000000 1
    #,###.#, 12345.678 12,345.7
    #,###.# 12345.678 12,345.7
         
: Time separator. This separates hours, minutes & seconds while formatting time values. hh:mm:ss AMPM 0.251 06:01:26 AM
         
/ (forward slash) Date separator. This separates the day, month & year while formatting date values. dd/mm/yyyy 7/24/2014 24/07/2014
    mm/dd/yyyy 41476 07/21/2013
         
E+   E-   e+   e- Scientific notation (exponential format). «E+» and «E-» followed by atleast one digit placeholder (0 or #), displays the number in scientific notation, with the character «E»  mentioned between the number and the exponent. The number of «0» characters determine the minimum number of exponent digits. «E+» indicates that the sign character (plus or minus) will always precede the exponent, whereas «E-» indicates that the sign character (minus) precedes only negative exponents. 0.00E+0 4560000 4.56E+6
  The E stands for exponent. To avoid writing extremely long numbers, use scientific notation (SN), ie. a numeric value containing the letter E followed by a number. To convert a SN number say 5.0E+3 to the actual number, move the decimal position 3 positions to the right OR multiply the number to the left of E by 10 raised to the powerof 3 viz. the actual number is 5000. If the exponent is negative, like in 5.25E-3, move the decimal position 3 positions to the left OR multiply the number to the left of E by 10 raised to the power of -3 viz. the actual number is 0.00525. #0.0E+00 4560000 45.6E+05
    0.###E+0 123.456 1.235E+2
    ##E+# 0.0001234 12E-5
    ##E-0 123456 12E4
    ##E+0 123456 12E+4
    ##E-0 0.0001234 12E-5
    0.##E+0 0.00525 5.25E-3
         
$  +  —  (  )  space Literal characters. These  are displayed as literals (exactly as typed) as per their position in the format code. Use these to display currency, to differentiate positive and negative numbers and for a more user-friendly display. $ +#,###.00 1456.7 $ +1,456.70
         
(backslash) Backslash. Any character appearing after backslash () will display as a literal, even though it may be reserved as an operator (say, %). Backlash itself will not be displayed. The number 0.75 with the format code #.00% will format to 75.00%, but with the format code #.00% it will format to .75%, ie. format code will not use % as operator but as a literal. To display several characters as literals enclose these in double quotation marks (» «) or in case of a single character, precede it with a backslash (). #.00% 0.75 .75%
  Many Characters do not display as literal, except when preceded with a backlash — some examples are: date/ time-formatting characters (c, d, h, m, n, q, s, w, y, / and :), the numeric-formatting characters (#, 0, and period), and string-formatting characters (@, &, <, >, and !). #.00% 0.75 75.00%
  Precede String with «Hello « Hello @ Tracy Hello Tracy
  character c does not display as literal, unless preceded with a backlash c @ Tracy Tracy
  character c does not display as literal, unless preceded with a backlash c @ Tracy c Tracy
  character b displays as literal, without being preceded with a backlash b @ Tracy b Tracy
  » kg” will be added to the end of the number 0 kg 75 75 kg
         
(» «) double quotation marks The string between the double quotation marks («») is displayed.      
  The vba Chr function returns a character (string data type) identified to the specified character code — use Chr(34) in your code for a quotation mark («) ex. MsgBox Chr(34) & ActiveCell.Value & Chr(34) returns the ActiveCell value within double quotation marks.      

Example: Using User-defined Number formats with the VBA Format Function.

Sub UserDefinedNumberFormats()
‘Using User-defined Number formats with the VBA Format Function.

Dim str As Variant

‘returns «5678.95»

str = Format(5678.9523, «0.00«)

MsgBox str

‘returns «05.90»

str = Format(5.9, «00.00«)

MsgBox str

‘returns «5.9»

str = Format(5.9, «##.##«)

MsgBox str

‘returns «5.95»

str = Format(5.9523, «##.00«)

MsgBox str

‘returns «5679»

str = Format(5678.9523, «#«)

MsgBox str

‘returns «$5672.5»

str = Format(5672.4523, «##.#«)

MsgBox str

‘returns «5,678.95»

str = Format(5678.9523, «#,###.##«)

MsgBox str

‘returns «(456) 789 — 1234»

str = Format(4567891234#, «(###) ### — ####«)

MsgBox str

‘returns «.63%»

str = Format(0.00625, «#.##%«)

MsgBox str

‘returns «%1»

str = Format(0.625, «%#«)

MsgBox str

‘returns «4.56E+6»

str = Format(4560000, «0.00E+0«)

MsgBox str

‘returns «45.6E+05»

str = Format(4560000, «#0.0E+00«)

MsgBox str

‘returns «12E4»

str = Format(123456, «##E-0«)

MsgBox str

‘returns «12E+4»

str = Format(123456, «##E+0«)

MsgBox str

‘returns «$ +1,456.70»

str = Format(1456.7, «$ +#,###.00«)

MsgBox str

‘returns «Hello Tracy»

str = Format(«Tracy«, «Hello @«)

MsgBox str

‘returns «75 kg»

str = Format(«75«, «0 kg»)

MsgBox str

End Sub

VBA Format Function can have upto Four Sections for User-defined Formats, for different Formats for different Numeric Values

While creating User-Defined Number Formats with the VBA Format Function, you can have upto 4 sections, each section being separated by semicolons(;), wherein you can create different formats for different Numeric values. Creating multiple sections is not possible wherein the format argument contains any Predefined Named Numeric format.

There can be upto four sections of format argument, wherein each section is separated by a semicolon. These sections determine the display of positive values, negative values, zeros and Null values, in that order. If only one section is specified, it applies to all values; if two sections are specified, the first applies to positive and zero values and the second section applies to negative values. When you use 3 sections for format argument, the first section applies to positive values, the second section applies to negative values, and the third section applies to zeros.

Example: Using multiple sections for user-defined Number formats with the VBA Format Function.

Sub MultipleSectionsUserDefinedNumberFormats()
‘Using multiple sections for user-defined Number formats with the VBA Format Function.

Dim str As Variant

‘returns «5,678.952»

str = Format(5678.9523, «#,###.000;($ #,##0);0.00;Null«)

MsgBox str

‘returns «($ 5,679)»

str = Format(-5678.9523, «#,###.000;($ #,##0);0.00;Null«)

MsgBox str

‘returns «0.00»

str = Format(0, «#,###.000;($ #,##0);0.00;Null«)

MsgBox str

End Sub

Missing a Section:

You can also skip a section and specify format argument for the following or preceding section, but then you must enter the ending semicolon for the skipped section. The skipped section is printed using the format of the positive value, and in the absence of a format for a positive value, skipping a section will result in a blank display for that section. See below example.

Example: Missing sections for user-defined Number formats with the VBA Format Function.

Sub MissingSectionsUserDefinedNumberFormats()
‘missing sections for user-defined Number formats with the VBA Format Function.

Dim str As Variant

‘returns «» ie. blank (positive expression, but no format argument for positive value)
str = Format(5678.9523, «;($ #,##0);Zero;«)
MsgBox str

‘returns «-5,678.952» (for negative expression, using the format of the positive value when no format argument for negative value)
str = Format(-5678.9523, «#,###.000;;Zero«)
MsgBox str

‘returns «» ie. blank (negative expression, no format argument for positive or negative values)
str = Format(-5678.9523, «;;«)
MsgBox str

‘returns «($ 5,679)» (for negative expression, using format argument for negative values)
str = Format(-5678.9523, «;($ #,##0);«)
MsgBox str

‘returns «zero» (for zero expression, using format argument for zero values)
str = Format(0, «;;zero«)
MsgBox str

‘returns «.000» (for zero expression, using the format of the positive value)

str = Format(0, «#,###.000;;«)

MsgBox str

End Sub

Characters used to create User-Defined Date & Time Formats with the VBA Format Function

Character Description Format Argument Expression Argument Formatted Display
/ (forward slash) Date separator. Separates the day, month & year while formatting date values. mm/dd/yyyy 41463 07/08/2013
c Date is displayed as ddddd and time is displayed as ttttt, in that order. Only date is displayed if date serial number does not have a fractional part and only time information is displayed if no integer portion. c 41463.251 7/8/2013 6:01:26 AM
    c 0.251 6:01:26 AM
    c 41463 7/8/2013
d Day is displayed as a number, as one digit or as two digit, without a leading zero. (1-31) mm/d/yyyy 41463 07/8/2013
dd Day is displayed as a number, as two digit, with a leading zero where applicable. (01-31) mm/dd/yyyy 41463 07/08/2013
ddd Day is abbreviated to three letters, viz. Sunday is displayed as Sun. (Sun-Sat) ddd, mmm d, yyyy 41463 Mon, Jul 8, 2013
dddd Day is displayed in its full format, viz. Sunday is displayed as Sunday. (Sunday-Saturday) dddd, mmm d, yyyy 41463 Monday, Jul 8, 2013
ddddd Display a date serial number as a complete date (including day, month, and year) formatted according to the short date setting recognized by your system. The default short date format is m/d/yy. ddddd 41463 7/8/2013 (Short Date Format in the system showing the display is: dddd, m/d/yyyy)
dddddd Display a date serial number as a complete date (including day, month, and year) formatted according to the long date setting recognized by your system. The default long date format is mmmm dd, yyyy. dddddd 41463 Monday, July 8, 2013  (Long Date Format in the system showing the display is: dddd, MMMM d, yyyy)
aaaa Displays the full, localized name of the day in its full format (same as dddd, except that its localized version).       
w Day of the week is displayed as a number (1-7 for Sunday-Saturday).  w, mmm d, yyyy  41463 2, Jul 8, 2013 
ww  Week of the year is displayed as a number. (1 to 54) ww #7/8/2013# 28
m Month is displayed as a number, as one digit or as two digit, without a leading zero — (1-12).  To use m as minute(s), it should appear immediately after the h or hh code, such as «h:m».  m/d/yyyy 41463 7/8/2013 
mm Month is displayed as a number, as two digit, with a leading zero where applicable — (01-12). To use mm as minute(s), it should appear immediately after the h or hh code, such as «h:mm».  mm/d/yyyy  41463 07/8/2013 
mmm Month name is abbreviated to three letters, viz. January is displayed as Jan. (Jan-Dec)  mmm d, yyyy  41463 Jul 8, 2013 
mmmm Month is displayed in its full name, viz. January is displayed as January. (January-December)  mmmm d, yyyy  41463 July 8, 2013 
oooo Displays the full localized name of the month (same as mmmm, except that its localized version).      
q Quarter of the year is displayed as a number. (1 to 4)  q #7/8/2013#  3
y Day of the year is displayed as a number. (1 to 366)  y #7/8/2013#  189
yy Year is displayed as a number in two digits, viz. last 2 digits of the year are displayed. (00-99)  m/d/yy  41463 7/8/13 
yyyy Year is displayed as a number in four digits, viz. all digits of the year are displayed. (1900-9999)  m/d/yyyy  41463 7/8/2013 
         
Time separator. This separates hours, minutes & seconds while formatting time values.  h:n:ss AMPM  0.251 6:1:26 AM 
h Hour is displayed as a number, as one digit or as two digit, without leading zeros. (0-23)  h:nn:ss AMPM  0.251 6:01:26 AM 
Hh Hour is displayed as a number, as two digit, with a leading zero where applicable. (00-23)  Hh:n:ss AMPM  0.251 06:1:26 AM 
N Minute is displayed as a number, as one digit or as two digit, without leading zeros —  (0 to 59). You can also use m code as minute (m is used for displaying month), for which it should appear immediately after the h or hh code, such as «h:m».  n:ss  0.251 1:26
Nn Minute is displayed as a number, as two digit, with a leading zero where applicable —  (00 to 59). You can also use m code as minute (m is used for displaying month), for which it should appear immediately after the h or hh code, such as «h:m».  Nn:s  0.251 01:26 
S Second is displayed as a number, as one digit or as two digit, without leading zeros. (0 — 59)  h:n:S 0.2591 6:13:6 
Ss Second is displayed as a number, as two digit, with a leading zero where applicable.  (00 — 59)  h:n:Ss 0.2591 6:13:06 
t t t t t   Complete time is displayed (including hour, minute, and second) wherein the time separator, as defined by the time format recognized by your system, is used. If the leading zero option is selected and the time is before 10:00 AM / PM, a leading zero will be displayed. h:mm:ss is the default format.  ttttt  0.25631  6:09:05 AM 
AM/PM, am/pm, A/P, a/p or AMPM If these codes are included in the format, the hour is displayed using a 12-hour clock, else the hour is based on the 24-hour format. Display will include AM, am, A or a for a time before noon, and PM, pm, P or p for a time ‘from’ and ‘after’ noon till 11:59 PM. While using AMPM, the case can be UPPER or lower, matching the string as defined by your system settings. AM/PM is the Default format. Hh:n:ss A/P 0.251 06:1:26 A

Example: Using User-defined Date & Time formats with the VBA Format Function.

Sub UserDefinedDateTimeFormats()
‘returns the Date and Time per user defined format

Dim MyDate As Variant, MyTime As Variant, str As Variant

MyDate = #7/1/2014#
MyTime = #7:09:32 PM#

‘returns «07/01/2014»

str = Format(MyDate, «mm/dd/yyyy«)

MsgBox str

‘returns «07/08/2013»

str = Format(41463, «mm/dd/yyyy«)

MsgBox str

‘returns «7/8/13»

str = Format(41463, «m/d/yy«)

MsgBox str

‘returns «7/8/2013 6:01:26 AM» — Date is displayed as ddddd and time is displayed as ttttt, in that order.

str = Format(41463.251, «c»)

MsgBox str

‘returns «6:01:26 AM» — only time information is displayed if no integer portion.

str = Format(0.251, «c«)

MsgBox str

‘returns «2» — Day of the week is displayed as a number (1-7 for Sunday-Saturday).

str = Format(41463, «w«)

MsgBox str

‘returns «28» — Week of the year is displayed as a number (1 to 54).

str = Format(#7/8/2013#, «ww«)

MsgBox str

‘returns «3» — Quarter of the year is displayed as a number (1 to 4)

str = Format(#7/8/2013#, «q«)

MsgBox str

‘returns «189» — Day of the year is displayed as a number (1 to 366)

str = Format(#7/8/2013#, «y«)

MsgBox str

‘returns «7/1/14»

str = Format(MyDate, «m/d/yy«)

MsgBox str

‘returns «Tue, Jul 1, 2014»

str = Format(MyDate, «ddd, mmm d, yyyy«)

MsgBox str

‘returns «19:9:32»

str = Format(MyTime, «h:n:s«)

MsgBox str

‘returns «07:09:32 pm»

str = Format(MyTime, «hh:mm:ss am/pm«)

MsgBox str

‘returns «07:09:32 PM»

str = Format(MyTime, «hh:mm:ss AMPM«)

MsgBox str

‘returns «06:1:26 A»

str = Format(0.251, «Hh:n:ss A/P«)

MsgBox str

‘returns «6:09:05 AM» — Complete time is displayed (including hour, minute, and second)

str = Format(0.25631, «ttttt«)

MsgBox str

‘omitting the format argument will return a String representation of the number — «245»

str = Format(245)

MsgBox str

End Sub

Characters used to create User-Defined String Formats with the VBA Format Function

Character Description Format Argument Expression Argument Formatted Display
@ (at character) Character placeholder. Display actual character or space. If character appears in the position where @ apepars in the format string, the character is displayed, else a space is displayed at that position. Placeholders will be filled from right to left, unless exclamation (!) character is used in the format string as explained below. @@@@@@@ Excel   Excel
(2 leading spaces appear on the left of «Excel»)
  Precede String with «Mr « «Mr «@ James Mr James
  Precede String with «Hello « Hello @ Tracy Hello Tracy
& Character placeholder. Display actual character or nothing. If character appears in the position where & (ampersand) appears in the format string, the character is displayed, else a nothing is displayed at that position. Placeholders will be filled from right to left, unless exclamation (!) character is used in the format string as explained below. &&&&&&&&& Excel VBA Excel VBA
(Displays «Excel VBA» as in the String)
> Displays all characters as uppercase. > Excel EXCEL
< Displays all characters as lowercase. < Excel excel
! Placeholders will be filled from left to right — Default is right to left. !@@@@@@@ Excel Excel  
(2 spaces appear on the right of «Excel»)

Example: Using User-defined String formats with the VBA Format Function.

Sub UserDefinedStringFormats()
‘Using User-defined String formats with the VBA Format Function.

Dim str As Variant

‘returns »  Excel» & 7 — (2 leading spaces appear on the left of «Excel»)

str = Format(«Excel«, «@@@@@@@«)

MsgBox str

MsgBox Len(str)

‘returns «Excel  » & 7 — (2 leading spaces appear on the right of «Excel»)

str = Format(«Excel«, «!@@@@@@@«)

MsgBox str

MsgBox Len(str)

‘returns «Mr James» — Precede String with «Mr «

str = Format(«James«, «««Mr ««@«)

MsgBox str

‘returns «Hello Tracy» — Precede String with «Hello «

str = Format(«Tracy«, «Hello @«)

MsgBox str

‘returns «EXCEL» — Displays all characters as uppercase.

str = Format(«Excel«, «>«)

MsgBox str

‘returns «excel» — Displays all characters as lowercase.

str = Format(«Excel«, «<«)

MsgBox str

End Sub

VBA Format Function can have One or Two Sections for User-defined Formats, for different Formats for different String Values

While creating User-Defined String Formats with the VBA Format Function, you can have One or Two sections, each section being separated by semicolons(;), wherein you can create different formats for different String values. If only one section is specified, it applies to all string data; if two sections are specified, the first applies applies to string data, and the second section applies to Null values and zero-length strings («»).

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

Понравилась статья? Поделить с друзьями:
  • Excel vba абсолютная ссылка в excel
  • Excel vba time from date
  • Excel vba xlsm xlsx
  • Excel vba time formats
  • Excel vba worksheetfunction trim