Return to VBA Code Examples

VBA DateDiff Function

DateDiff Description

Returns the difference between two date values, based on the interval specified.

Simple DateDiff Examples

Here is a simple DateDiff example:

This code will return 2. This is difference on year (indicated by “yyyy”) between 2 days. (2021 – 2019 = 2)

In the example above, changing the positions of date1 and date2.

This code will return -2.

DateDiff Syntax

In the VBA Editor, you can type  “DateDiff(” to see the syntax for the DateDiff Function:

The DateDiff function contains 5 arguments:

Interval: Time unit (Days, Months, Years, etc.). Enter as string. (ex. “m” for Month)

Setting Description
yyyy Year
q Quarter
m Month
y Day of Year
d Day
w Weekday
ww Week
h Hour
n Minute
s Second

Date1, Date2: Two dates you want to use in the calculation.

FirstDayOfWeek: A constant that specifies the first day of the week. This is optional. If not specified, Sunday is assumed.

Constant Value Description
vbUseSystem 0 Use the NLS API setting.
vbSunday 1 Sunday (default)
vbMonday 2 Monday
vbTuesday 3 Tuesday
vbWednesday 4 Wednesday
vbThursday 5 Thursday
vbFriday 6 Friday
vbSaturday 7 Saturday

FirstWeekOfYear: A constant that specifies the first week of the year. This is optional. If not specified, the first week is assumed to be the week in which January 1 occurs.

Constant Value Description
vbUseSystem 0 Use the NLS API setting.
vbFirstJan1 1 Start with week in which January 1 occurs (default).
vbFirstFourDays 2 Start with the first week that has at least four days in the new year.
vbFirstFullWeek 3 Start with first full week of the year.

 

Examples of Excel VBA DateDiff Function

Referencing Dates

To start, we will demonstrate different ways to reference dates using the VBA DateDiff Function.

Each of these DateDiff functions produce the same result:

Or you can reference cells containing dates:

Or create and reference date variables:

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!!

Using Different Units of Interval

Quarters

Months

Days

Weeks

Hours

Minutes

Seconds