Getting and formatting the date and time with VBA

When creating a script it is often powerful to include the date or the time. The following example shows how to get the current date and time and then how to format this information in a presentable way suitable for your application.

Sub dateTimeExamples()

MsgBox (Date) ' Returns 15/02/2020

Dim day As Date
day = Date

MsgBox (Format(day, "Long Date"))   ' Returns 15 February 2020
MsgBox (Format(day, "dddd"))        ' Returns Saturday
MsgBox (Format(day, "dd"))          ' Returns 15
MsgBox (Format(day, "mm"))          ' Returns 02
MsgBox (Format(day, "yy"))          ' Returns 20
MsgBox (Format(day, "yyyy"))        ' Returns 2020

Dim now As Date
now = Time

MsgBox (now)                       ' 22:38:12

MsgBox (Format(now, "ss"))          ' Returns 12
MsgBox (Format(now, "mm"))          ' Returns 38
MsgBox (Format(now, "hh"))          ' Returns 22
MsgBox (Format(now, "hh:mm:ss"))    ' Returns 22:38:12
MsgBox (Format(now, "hh:mm"))       ' Returns 22:38

End Sub

Related Sections

Python - Learn the python from the basics up. This fast track example code course will get you creating powerful python programs in no time.

Must Read Articles

VBA and Microsoft Excel - Getting the most out of excel with VBA programming
VBA and Microsoft Word - Getting the most out of word with VBA programming
Application Object - Using the applications features in your code.

Installing VBA and First Program - What do you need to start using visual basic application VBA.