totn Excel Functions

MS Excel: How to use the DATEDIFF Function (VBA)

This Excel tutorial explains how to use the Excel DATEDIFF function with syntax and examples.

Description

The Microsoft Excel DATEDIFF function returns the difference between two date values, based on the interval specified.

The DATEDIFF function is a built-in function in Excel that is categorized as a Date/Time Function. It can be used as a VBA function (VBA) in Excel. As a VBA function, you can use this function in macro code that is entered through the Microsoft Visual Basic Editor.

Syntax

The syntax for the DATEDIFF function in Microsoft Excel is:

DateDiff( interval, date1, date2, [firstdayofweek], [firstweekofyear] )

Parameters or Arguments

interval

The interval of time to use to calculate the difference between date1 and date2. Below is a list of valid interval values.

Interval Explanation
yyyy Year
q Quarter
m Month
y Day of year
d Day
w Weekday
ww Week
h Hour
n Minute
s Second
date1 and date2
The two dates to calculate the difference between.
firstdayofweek
Optional. It is a constant that specifies the first day of the week. If this parameter is omitted, it assumes that Sunday is the first day of the week.
firstweekofyear
Optional. It is a constant that specifies the first week of the year. If this parameter is omitted, it assumes that the week containing Jan 1st is the first week of the year.

Returns

The DATEDIFF function returns a numeric value.

Applies To

  • Excel for Office 365, Excel 2019, Excel 2016, Excel 2013, Excel 2011 for Mac, Excel 2010, Excel 2007, Excel 2003, Excel XP, Excel 2000

Type of Function

  • VBA function (VBA)

Example (as VBA Function)

The DATEDIFF function can only be used in VBA code in Microsoft Excel.

Let's look at some Excel DATEDIFF function examples and explore how to use the DATEDIFF function in Excel VBA code:

DateDiff("yyyy", "22/11/2003", "22/11/2013")
Result: 10

DateDiff("q", "22/11/2003", "22/11/2013")
Result: 40

DateDiff("m", "22/11/2011", "1/1/2012")
Result: 2

For example, you could use the DATEDIFF function in VBA code and create the following function:

Function TestDates (pDate1 as Date, pDate2 as Date) as Long

   TestDates = DateDiff("d", pDate1, pDate2)

End Function

Microsoft Excel

Based on the spreadsheet above, the following Excel function would return the following values:

=TestDates(A2, A1)
Result: 1

=TestDates(A2, A3)
Result: 349

=TestDates(A4, A3)
Result: 14