Key Learning Points: In this lesson, you'll learn how to work with dates and times in Excel VBA, including retrieving system dates/times, extracting components, and performing calculations.
Excel VBA provides powerful built-in date and time functions that allow you to:
These functions help you work with calendar dates in your VBA applications:
Function | Description | Example Usage |
---|---|---|
Now |
Returns current system date and time | Cells(1,1) = Now |
Date |
Returns current system date | Cells(1,1) = Date |
Day(Date) |
Returns day of month (1-31) | Day("12/25/2023") → 25 |
Weekday(Date) |
Returns weekday as number (1=Sunday) | Weekday(Date) |
WeekdayName() |
Returns weekday name (full or abbreviated) | WeekdayName(Weekday(Date)) |
Month(Date) |
Returns month number (1-12) | Month("12/25/2023") → 12 |
MonthName() |
Returns month name (full or abbreviated) | MonthName(Month(Date)) |
Year(Date) |
Returns the year | Year(Date) |
This example demonstrates how to extract and display various date components in Excel:
Private Sub CommandButton1_Click()
' Display various date components in column B
Cells(1, 2) = Now ' Current date and time
Cells(2, 2) = Date ' Current date
Cells(3, 2) = Day(Date) ' Day of month
Cells(4, 2) = Weekday(Date) ' Weekday number
Cells(5, 2) = WeekdayName(Weekday(Date)) ' Full weekday name
Cells(6, 2) = WeekdayName(Weekday(Date), True) ' Abbreviated weekday
Cells(7, 2) = Month(Date) ' Month number
Cells(8, 2) = MonthName(Month(Date)) ' Full month name
Cells(9, 2) = MonthName(Month(Date), True) ' Abbreviated month
Cells(10, 2) = Year(Date) ' Current year
End Sub
Pro Tip: Use Format()
function to display dates in custom formats like "dd-mmm-yyyy" or "mmmm d, yyyy".
Excel VBA also provides functions specifically for working with times:
Function | Description | Example Usage |
---|---|---|
Time |
Current system time | Cells(1,1) = Time |
Hour(time) |
Hour component (0-23) | Hour("3:45 PM") → 15 |
Minute(time) |
Minute component (0-59) | Minute(Now) |
Second(time) |
Second component (0-59) | Second(Time) |
Timer |
Seconds since midnight | Timer |
This example shows how to work with time values in VBA:
Private Sub CommandButton1_Click()
' Display various time components in column B
Cells(1, 2) = Time ' Current time
Cells(2, 2) = Hour(Time) ' Current hour
Cells(3, 2) = Minute(Time) ' Current minute
Cells(4, 2) = Second(Time) ' Current second
Cells(5, 2) = Timer ' Seconds since midnight
' Bonus: Calculate time difference
Dim startTime As Double
startTime = Timer
' ... some code that takes time to execute ...
Cells(6, 2) = Timer - startTime & " seconds elapsed"
End Sub
Share this lesson:
Copyright ® 2008- Dr. Liew Voon Kiong. All rights reserved [Privacy Policy]
Contact: Facebook Page | Email