VBA course · Lesson 13 of 33
Working with dates and times in VBA
Handle dates safely in VBA: Date, Now, DateSerial, DateAdd, DateDiff, Year/Month/Day, Weekday, Format, date literals and the CDate locale trap.
Dates are everywhere in business workbooks: invoice dates, due dates, hire dates, delivery dates, the reporting month in a file name. They are also one of the most common sources of bugs in VBA, mostly because the same text, such as 03/04/2026, means 3 April in Europe and March 4 in the United States. This lesson shows how VBA stores dates, how to create and calculate them reliably, and how to avoid the locale traps.
How dates are stored
In VBA, as in Excel, a date is really a number. The whole part counts days, and the decimal part is the time of day as a fraction of 24 hours. In the worksheet, day 1 is 1 January 1900, so 1 January 2026 is serial number 46023 and 15 March 2026 is 46096. Noon is 0.5, 6:00 pm is 0.75.
VBA has its own Date data type that holds a date and time together. When you read a date cell into a Date variable, or write one back, VBA converts between the two systems for you, so for modern dates you rarely need to think about the serial number. But it explains a lot: you can subtract two dates to get the number of days between them, and add 30 to a date to move 30 days on.
Option Explicit
Sub DateBasics()
Dim invoiceDate As Date
Dim dueDate As Date
invoiceDate = DateSerial(2026, 3, 15)
dueDate = invoiceDate + 30
Debug.Print dueDate ' 14/04/2026 or 4/14/2026, depending on regional settings
Debug.Print dueDate - invoiceDate ' 30
Debug.Print CLng(invoiceDate) ' 46096, the same serial number as in the sheet
End SubDate values, not raw numbers, and you never have to care.Today and now: Date, Now, Time
Datereturns today's date with no time (like TODAY).Nowreturns today's date and the current time (like NOW).Timereturns only the current time.
These are VBA functions, evaluated once when the line runs; unlike the worksheet functions they never recalculate by themselves. That makes them perfect for timestamps: Range("F2").Value = Now records the moment a row was processed and the value stays fixed.
Building dates safely: DateSerial and TimeSerial
DateSerial(year, month, day) builds a date from three numbers. Because it never involves text, it works identically on every computer in every country. It also rolls over gracefully:
DateSerial(2026, 13, 1)is 1 January 2027.DateSerial(2026, 3, 0)is the day before 1 March, which is 28 February 2026. Day 0 of the next month is a well-known trick to get the last day of any month.DateSerial(2026, 1, 1 + 90)is 1 January plus 90 days.
TimeSerial(hour, minute, second) does the same for times, and you can add the two: DateSerial(2026, 3, 15) + TimeSerial(14, 30, 0) is 15 March 2026 at 2:30 pm.
Date literals: #...#
You can write a fixed date directly in code between hash signs. The safe form is ISO order, year-month-day: #2026-03-15#. The VBA editor immediately rewrites it in its own fixed US format as #3/15/2026#. That is normal: date literals in code are always interpreted as month/day/year, regardless of your regional settings. So #3/4/2026# is always March 4, even on a European PC. If you type literals yourself, use the ISO form or DateSerial and let the editor convert it.
Taking dates apart: Year, Month, Day, Weekday
| Function | Returns for 15 Mar 2026 (a Sunday) |
|---|---|
| Year(d) | 2026 |
| Month(d) | 3 |
| Day(d) | 15 |
| Weekday(d) | 1 (Sunday = 1 by default) |
| Weekday(d, vbMonday) | 7 (Monday = 1) |
| WeekdayName(Weekday(d)) | Sunday |
| MonthName(Month(d)) | March |
| Hour(t), Minute(t), Second(t) | Parts of a time |
The optional second argument of Weekday sets the first day of the week. With vbMonday, Saturday is 6 and Sunday is 7, so Weekday(d, vbMonday) > 5 is a neat weekend test. WeekdayName and MonthName return names in the language of the computer's regional settings.
Date arithmetic: DateAdd and DateDiff
Adding days is easy with +, but months and years have different lengths. DateAdd(interval, number, date) does the calendar maths for you:
| Interval | Unit |
|---|---|
| "d" | Day |
| "ww" | Week |
| "m" | Month |
| "q" | Quarter |
| "yyyy" | Year |
| "h", "n", "s" | Hour, minute ("n", not "m"), second |
DateAdd("m", 1, #2026-01-31#) gives 28 February 2026: when the target month is shorter, VBA uses its last day, the same as EDATE.
DateDiff(interval, date1, date2) counts how many interval boundaries lie between two dates. That wording matters: DateDiff("yyyy", #2025-12-31#, #2026-01-01#) is 1, although only one day has passed, because a year boundary was crossed. For whole years of age or service you need a correction:
Option Explicit
Function YearsOfService(ByVal hireDate As Date, ByVal onDate As Date) As Long
Dim y As Long
y = DateDiff("yyyy", hireDate, onDate)
' Subtract one if this year's anniversary has not been reached yet
If DateSerial(Year(onDate), Month(hireDate), Day(hireDate)) > onDate Then
y = y - 1
End If
YearsOfService = y
End Function
Sub ServiceReport()
Dim r As Long
For r = 2 To 5
Cells(r, "C").Value = YearsOfService(Cells(r, "B").Value, Date)
Next r
End SubThe worksheet function DATEDIF does the same in a cell. DateDiff("d", d1, d2) is simply d2 - d1, and DateDiff("m", ...) counts month boundaries.
A worked example: due dates and overdue days
| A | B | C | D | E | |
|---|---|---|---|---|---|
| 1 | Invoice | Date | Terms | Due | Days late |
| 2 | INV-2001 | 2026-01-10 | 30 | ||
| 3 | INV-2002 | 2026-02-03 | 14 | ||
| 4 | INV-2003 | 2026-02-20 | 60 | ||
| 5 | INV-2004 | 2026-03-01 | 30 |
Before: invoice dates and payment terms (in days)
Option Explicit
Sub DueDates()
Dim r As Long
Dim dueDate As Date
Dim today As Date
today = DateSerial(2026, 3, 20) ' use Date in real life; fixed here so the result is repeatable
For r = 2 To 5
dueDate = Cells(r, "B").Value + Cells(r, "C").Value
' If the due date falls on a weekend, move it to Monday
Select Case Weekday(dueDate, vbMonday)
Case 6: dueDate = dueDate + 2 ' Saturday
Case 7: dueDate = dueDate + 1 ' Sunday
End Select
Cells(r, "D").Value = dueDate
Cells(r, "D").NumberFormat = "yyyy-mm-dd"
If today > dueDate Then
Cells(r, "E").Value = today - dueDate
Else
Cells(r, "E").Value = 0
End If
Next r
End Sub| A | B | C | D | E | |
|---|---|---|---|---|---|
| 1 | Invoice | Date | Terms | Due | Days late |
| 2 | INV-2001 | 2026-01-10 | 30 | 2026-02-09 | 39 |
| 3 | INV-2002 | 2026-02-03 | 14 | 2026-02-17 | 31 |
| 4 | INV-2003 | 2026-02-20 | 60 | 2026-04-21 | 0 |
| 5 | INV-2004 | 2026-03-01 | 30 | 2026-03-31 | 0 |
After: INV-2002 was due on Tuesday 17 Feb; INV-2001 on Monday 9 Feb
The Case 6: dueDate = dueDate + 2 lines use a colon to put two statements on one line, a common compact style inside Select Case. For real working-day calculations including public holidays, the worksheet function WORKDAY is easier: Application.WorksheetFunction.WorkDay(startDate, 10, holidayRange).
Formatting dates
There are two separate things: the value in a cell and how it is displayed. To change only the display, set NumberFormat, as above. To turn a date into text, for a message or a file name, use Format:
Option Explicit
Sub DateText()
Dim d As Date
d = DateSerial(2026, 3, 15) + TimeSerial(9, 5, 0)
Debug.Print Format(d, "yyyy-mm-dd") ' 2026-03-15 (sorts correctly as text)
Debug.Print Format(d, "dd mmm yyyy") ' 15 Mar 2026
Debug.Print Format(d, "dddd d mmmm") ' Sunday 15 March
Debug.Print Format(d, "hh:nn") ' 09:05 (nn = minutes)
Debug.Print "Report_" & Format(Date, "yyyymmdd") & ".xlsx"
End SubIn Format, m means month and n means minute (hh:mm also works in most cases because VBA recognises the context, but nn is unambiguous). For file names, yyyy-mm-dd is the best choice: it sorts in date order, avoids slashes (which are not allowed in file names) and means the same thing everywhere.
The CDate and text-date trap
Problems start when dates arrive as text, for example from a CSV file or a text box: "03/04/2026". CDate and DateValue convert text to a date using the computer's regional settings. On a UK PC CDate("03/04/2026") is 3 April; on a US PC it is March 4. Your macro gives different answers on different machines, and nobody gets an error.
Worse, when a day is greater than 12, the conversion may silently swap the order to make it valid. "13/04/2026" becomes 13 April even on a US machine, so a column ends up with a mix of correct and wrong dates.
The robust approach is to take the text apart yourself and build the date with DateSerial:
Option Explicit
Function DmyToDate(ByVal s As String) As Variant
Dim parts() As String
parts = Split(Trim(s), "/")
If UBound(parts) <> 2 Then
DmyToDate = CVErr(xlErrValue) ' shows #VALUE! if used in a cell
Exit Function
End If
DmyToDate = DateSerial(CLng(parts(2)), CLng(parts(1)), CLng(parts(0)))
End Function
Sub FixImportedDates()
Dim cell As Range
For Each cell In Range("B2:B6")
If VarType(cell.Value) = vbString Then
cell.Value = DmyToDate(cell.Value)
cell.NumberFormat = "yyyy-mm-dd"
End If
Next cell
End SubVarType(...) = vbString checks that the cell holds text, so dates that Excel already recognised are left alone. IsDate(s) tells you whether text can be converted, but not which way it will be read, so it does not solve the ambiguity. In the sheet, the equivalent problem is fixed with DATE, LEFT, MID and RIGHT.
Date value, not a string. Range("B2").Value = "03/04/2026" lets Excel guess; Range("B2").Value = DateSerial(2026, 4, 3) is unambiguous.Common mistakes
- Using
"m"for minutes inDateAddorFormat; minutes are"n". - Trusting
DateDiff("yyyy", ...)for ages; correct for the anniversary. - Converting text dates with
CDatein workbooks used in several countries. - Writing dates as text into cells and then sorting or filtering them.
- Comparing a date with a time to
Date:Now > Dateis True all day, becauseNowincludes the time. UseInt(Now)orDateValueto drop the time part. - Forgetting that
Weekdaycounts Sunday as 1 unless you passvbMonday.
Check yourself
1. What does DateSerial(2026, 3, 0) return?
Day 0 means the day before the 1st, so it gives the last day of the previous month.
2. Which interval does DateAdd use for minutes?
"m" means months; minutes use "n".
3. What does DateDiff("yyyy", #2025-12-31#, #2026-01-01#) return?
DateDiff counts year boundaries crossed, not full years.
4. Why is CDate("03/04/2026") risky in a workbook used in several countries?
Text dates are read in the local order, so the same text can become 3 April or March 4.
5. Which format string gives text like 2026-03-15?
Year-month-day text sorts correctly and is unambiguous.