VBA DateDiff function in Excel is categorized as a Date & Time function. This is a built-in Excel VBA Function. This function returns the difference between two date values, based on the interval specified. We can use this function in VBA and can’t use in Excel.
This function we use in either procedure or function in a VBA editor window in Excel. We can use this VBA DateDiff Function in any number of times in any number of procedures or functions. Let us learn what is the syntax and parameters of the DateDiff function, where we can use this DateDiff Function and real-time examples in Excel VBA.
Table of Contents:
- Objective
- Syntax of VBA DateDiff Function
- Parameters or Arguments
- Where we can apply or use VBA DateDiff Function?
- Example 1: Compute the number of days
- Example 2: Compute the number of months
- Example 3: Compute the number of years
- Example 4: Compute the number of weeks
- Example 5: Compute the number of hours
- Instructions to Run VBA Macro Code
- Other Useful Resources
The syntax of the DateDiff Function in VBA is
DateDiff(Interval,Date1,Date2,[FirstDayOfWeek],[FirstWeekOfYear])
The DateDiff function returns a string value.
Parameters or Arguments:
The DateDiff function has five arguments in Excel VBA.
where
Interval:The Interval is a required argument. It represents the interval of time to calculate the difference between two Date1 and Date2. Here is a list of interval values.
Interval | Description |
---|---|
yyyy | Year |
q | Quarter |
m | Month |
y | Day of year |
d | Day |
w | Weekday |
ww | Week |
h | Hour |
n | Minute |
s | Second |
Date1:The Date1 is a required argument. It represents date.
Date2:The Date2 is a required argument. It represents date.
[FirstDayOfWeek]:The [FirstDayOfWeek] is an optional constant argument. It represents the first day of the week. If this argument is ignored, Sunday(vbSunday) is the default value.
VB Constant | Value | Description |
---|---|---|
vbUseSystem | 0 | Use the National Language Support(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]:The [FirstWeekOfYear] is an optional constant argument. It represents the first week of the year. If this argument is ignored, 1st Jan(vbFirstJan1) is the default value.
VB Constant | Value | Description |
---|---|---|
vbUseSystem | 0 | Use the National Language Support(NLS) API setting |
vbFirstJan1 | 1 | The week in which January 1 occurs (default) |
vbFirstFourDays | 2 | The first week consists at least four days in the year |
vbFirstFullWeek | 3 | The first full week of the year |
Where we can apply or use VBA DateDiff Function?
We can use this DateDiff Function in VBA MS Office 365, MS Excel 2016, MS Excel 2013, 2011, Excel 2010, Excel 2007, Excel 2003, Excel 2016 for Mac, Excel 2011 for Mac, Excel Online, Excel for iPhone, Excel for iPad, Excel for Android tablets and Excel for Android Mobiles.
Example 1: Compute the number of days between a start date and end date
Here is a simple example of the VBA DateDiff function. This below example computes the number of days between a start date and end date.
'Compute the number of days between a start date and end date Sub VBA_DateDiff_Function_Ex1() 'Variable declaration Dim sDate As Date Dim eDate As Date Dim iDate As Integer sDate = "02/04/2018" eDate = "04/06/2018" iDate = DateDiff("d", sDate, eDate) MsgBox "The number of days between " & sDate & " and " & eDate & " : " & iDate, vbInformation, "VBA DateDiff Function" End Sub
Output: Here is the screen shot of the first example output.
Example 2: Compute the number of months between a start date and end date
Let us see one more example of the VBA DateDiff function. This below example computes the number of months between a start date and end date.
'Compute the number of months between a start date and end date Sub VBA_DateDiff_Function_Ex2() 'Variable declaration Dim sDate As Date Dim eDate As Date Dim iDate As Integer sDate = "02/04/2018" eDate = "04/06/2018" iDate = DateDiff("m", sDate, eDate) MsgBox "The number of months between " & sDate & " and " & eDate & " : " & iDate, vbInformation, "VBA DateDiff Function" End Sub
Output: Here is the screen shot of the second example output.
Example 3: Compute the number of years between a start date and end date
Let us see another example of the VBA DateDiff function. This below example computes the number of years between a start date and end date.
'Compute the number of years between a start date and end date Sub VBA_DateDiff_Function_Ex3() 'Variable declaration Dim sDate As Date Dim eDate As Date Dim iDate As Integer sDate = "02/04/2018" eDate = "04/06/2025" iDate = DateDiff("yyyy", sDate, eDate) MsgBox "The number of years between " & sDate & " and " & eDate & " : " & iDate, vbInformation, "VBA DateDiff Function" End Sub
Output: Here is the screen shot of the third example output.
Example 4: Compute the number of weeks between a start date and end date
One more example of the VBA DateDiff function. This below example computes the number of weeks between a start date and end date
'Compute the number of weeks between a start date and end date Sub VBA_DateDiff_Function_Ex4() 'Variable declaration Dim sDate As Date Dim eDate As Date Dim iDate As Integer sDate = "02/04/2018" eDate = "04/06/2018" iDate = DateDiff("w", sDate, eDate) MsgBox "The number of weeks between " & sDate & " and " & eDate & " : " & iDate, vbInformation, "VBA DateDiff Function" End Sub
Output: Here is the screen shot of the fourth example output.
Example 5: Compute the number of hours between a start time and end time
One more example of the VBA DateDiff function. This below example computes the number of hours between a start time and end time.
'Compute the number of hours between a start time and end time Sub VBA_DateDiff_Function_Ex5() 'Variable declaration Dim sTime As Date Dim eTime As Date Dim iTime As Integer sTime = "02:04:10" eTime = "08:06:35" iTime = DateDiff("h", sTime, eTime) MsgBox "The number of hours between " & sTime & " and " & eTime & " : " & iTime, vbInformation, "VBA DateDiff Function" End Sub
Output: Here is the screen shot of the fifth example output.
Instructions to Run VBA Macro Code or Procedure:
You can refer the following link for the step by step instructions.
Instructions to run VBA Macro Code
Other Useful Resources:
Click on the following links of the useful resources. These helps to learn and gain more knowledge.
VBA Tutorial VBA Functions List VBA Arrays in Excel Blog
VBA Editor Keyboard Shortcut Keys List VBA Interview Questions & Answers
DateDiff Function in Excel VBA
VBA Datediff function provides the difference between two specified intervals. Here, the interval may be specified as hours/months/days… etc. as specified by the user. It is an inbuilt function in Excel and categorized as the “Date/Time” function. It can be used as a “VBA” function in Excel.
Syntax:
Parameters of DateDiff Function in Excel VBA
Parameter or Arguments used in DateDiff function.
1. Interval:
- It is mandatory.
- Type:- String type expression.
- It calculates the difference between the two dates.
Setting(interval) | Description/Explanation |
“s” | Seconds |
“n” | Minutes |
“h” | Hours |
“d” | Days |
“w” | Weekday |
“m” | Months |
“ww” | Week |
“y” | Day of the year |
“q” | Quarter |
“yyyy” | Year |
2. Date1:
- It is mandatory.
- Type:- Date.
- It represents the start date/time for the calculation of datediff.
3. Date2:
- It is mandatory.
- Type:- Date.
- It represents the end date/time for the calculation of datediff.
4. First day of the week:
- It is optional.
- Type:- Numeric or Text.
- It specifies the day that is used as the first day of the week.
- If this argument or parameter is omitted, it assumes Sunday(VbSunday) as the first day of the week.
5. First week of the year
- It is optional.
- Type:- Numeric or Text.
- It specifies the day that is used as the first week of the year.
- If this argument or parameter is omitted, it assumes January 1st (vbFirstJan1)as the first week of the year.
How to Enable Developer’s Tab in Excel?
The developer tab is mandatory on the Excel ribbon to start and write VBA macro. Below are the different steps to enable developers tab in excel VBA:
Step 1: Go to the File menu tab.
Step 2: In the File menu, click on Options situated at the last of the list available options under the menu.
Step 3: Click on Customize Ribbon to access the ribbon customization options.
Step 4: Here in the customization options, you can see the Developer option. Checkmark it, so that it gets activated on the main ribbon of excel and can easily be accessed. Click OK after checking the Developer option.
As soon as you hit OK, you can see the Developer tab active in the Excel ribbon menu with a bunch of different options available under. See the screenshot below.
How to Use the DateDiff Function in Excel VBA?
Below are the different steps to use the DateDiff Function in Excel VBA:
You can download this VBA DateDiff Excel Template here – VBA DateDiff Excel Template
Example #1
In this example, follow the below steps to use DateDiff Function in VBA:
Step 1: First create a macro name.
Code:
Sub bb() End Sub
Step 2: Two variables are defined as date and assigned date to them.
Code:
Sub bb() Dim dt1 As Date Dim dt2 As Date dt1 = #1/1/2010 9:00:00 AM# dt2 = #4/19/2019 11:00:00 AM# End Sub
Step 3: Write the syntax of the Datediff function taking the required argument and assign the same through the VBA message box.
Code:
Sub bb() Dim dt1 As Date Dim dt2 As Date dt1 = #1/1/2010 9:00:00 AM# dt2 = #4/19/2019 11:00:00 AM# MsgBox DateDiff("h", dt1, dt2) End Sub
Step 4: Run the code by pressing the F5 key or by clicking on the Play button. So that the result will be displayed in the message box.
Example #2
In the below example, the datediff function calculates the number of years between the two dates “09/06/2016” and “16/12/2020”. Here, optional parameters are not taken into consideration.
Code:
Sub AA() 'Year difference MsgBox DateDiff("yyyy", "09/06/2016", "16/12/2020") End Sub
To run the program press the “F8” or “Run” tab. The result will be displayed in the message box.
Example #3
In the below example, the datediff function calculates the number of months between the two dates ”09/06/2016” and “16/12/2020”. Here, optional parameters are not taken into consideration.
Code:
Sub AA1() 'month difference MsgBox DateDiff("m", "09/06/2016", "16/12/2020") End Sub
To run the program press the “F8” or “Run” tab. The result will be displayed in the message box.
Example #4
In the below example, the datediff function calculates the number of weeks between in the two dates ”09/06/2016” and “16/12/2020”. Here, optional parameters are not taken into consideration.
Code:
Sub AA2() 'weeks difference MsgBox DateDiff("ww", "09/06/2016", "16/12/2020") End Sub
To run the program press the “F8” or “Run” tab. The result will be displayed in the message box.
Example #5
In the below example, the “datediff” function calculates the number of quarters between the two dates” 09/06/2016” and “16/12/2020”. Here, optional parameters are not taken into consideration.
Code:
Sub AA3() 'quarter difference MsgBox DateDiff("q", "09/06/2016", "16/12/2020") End Sub
To run the program press the “F8” or “Run” tab. The result will be displayed in the message box.
Example #6
In the below example, the “datediff” function calculates the number of days between the two dates” 09/06/2016” and “16/12/2020”. Here, optional parameters are not taken into consideration.
Code:
Sub AA4() 'days difference MsgBox DateDiff("d", "09/06/2016", "16/12/2020") End Sub
To run the program press the “F8” or “Run” tab. The result will be displayed in the message box.
Example #7
In the below example, the “datediff” function calculates the number of hours between the two dates and time ”9:00 on 01/01/ 2010” and “11:00 on 19/04/ 2019”.
Code:
Sub bb1() 'Calculate the numberof hours between 1/1/2010 9:00 and 19/4/2019 11:00 Dim dt1 As Date Dim dt2 As Date dt1 = #1/1/2010 9:00:00 AM# dt2 = #4/19/2019 11:00:00 AM# MsgBox DateDiff("h", dt1, dt2) End Sub
To run the program press the “F8” or “Run” tab. The result will be displayed in the message box.
Example #8
In the below example, the “datediff” function calculates the number of seconds between the two dates and time ”9:00 on 01/01/ 2010” and “11:00 on 19/04/ 2019”.
Code:
Sub bb2() 'Calculate the number of seconds between 1/1/2010 9:00 and 19/4/2019 11:00 Dim dt1 As Date Dim dt2 As Date dt1 = #1/1/2010 9:00:00 AM# dt2 = #4/19/2019 11:00:00 AM# MsgBox DateDiff("s", dt1, dt2) End Sub
To run the program press the “F8” or “Run” tab. The result will be displayed in the message box.
Example #9
In the below example, the “datediff” function calculates the number of minutes between the two dates and time ”9:00 on 01/01/ 2010” and “11:00 on 19/04/ 2019”.
Code:
Sub bb3() 'Calculate the number of minutes between 1/1/2010 9:00 and 19/4/2019 11:00 Dim dt1 As Date Dim dt2 As Date dt1 = #1/1/2010 9:00:00 AM# dt2 = #4/19/2019 11:00:00 AM# MsgBox DateDiff("n", dt1, dt2) End Sub
To run the program press the “F8” or “Run” tab. The result will be displayed in the message box.
Example #10
If the argument is specified as “w”(weeks), the “Datediff” function returns the number of the whole week between the two dates. Partial weeks are ignored. In the example, the “DateDiff” function calculates the number of whole weeks between the dates 01/01/2010 and 19/4/2019.
Code:
Sub bb4() 'Calculate the number of weeks between 1/1/2010 and 19/4/2010 Dim dt1 As Date Dim dt2 As Date dt1 = #1/1/2010# dt2 = #4/19/2010# MsgBox DateDiff("w", dt1, dt2) End Sub
To run the program press the “F8” or “Run” tab. The result will be displayed in the message box.
Example #11
If the argument is specified as “ww”(calendar weeks), the “Datediff” function provides the number of weeks between the start of the week containing Date1 and the start of the week containing Date2.
Code:
Sub bb5() 'Calculate the number of calendar weeks between 1/1/2010 and 19/4/2019 ' First day of the week = Monday Dim dt1 As Date Dim dt2 As Date dt1 = #1/1/2010# dt2 = #4/19/2019# MsgBox DateDiff("ww", dt1, dt2, vbMonday) End Sub
To run the program press the “F8” or “Run” tab. The result will be displayed in the message box.
Example #12
In the below example, “datediff” function is used for dates”1/1/1990” and “1/1/1998”
Code:
Sub cc() Dim dt1 As Date Dim dt2 As Date dt1 = #1/1/1990 9:00:00 AM# dt2 = #1/11/1998 11:00:00 AM# MsgBox ("line 1:" & DateDiff("h", dt1, dt2)) MsgBox ("line 2:" & DateDiff("s", dt1, dt2)) MsgBox ("line 3:" & DateDiff("n", dt1, dt2)) MsgBox ("line 4:" & DateDiff("d", dt1, dt2)) MsgBox ("line 5:" & DateDiff("m", dt1, dt2)) MsgBox ("line 6:" & DateDiff("q", dt1, dt2)) MsgBox ("line 7:" & DateDiff("w", dt1, dt2)) MsgBox ("line 8:" & DateDiff("ww", dt1, dt2)) MsgBox ("line 9:" & DateDiff("y", dt1, dt2)) MsgBox ("line 10:" & DateDiff("yyyy", dt1, dt2)) End Sub
To run the program press the “F8” or “Run” tab. The result will be displayed in the message box.
Then, click on “Ok” to get the next result.
Conclusion
“DateDiff” function thus helps in determining how many specified time intervals exist between two specified dates and times.
Recommended Articles
This is a guide to VBA DateDiff. Here we discuss how to use DateDiff function in Excel VBA along with practical examples and downloadable excel template. You can also go through our other suggested articles –
- VBA Declare Array
- VBA on Error
- VBA Columns
- VBA Environ
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
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
In this Article
- DateDiff Description
- Simple DateDiff Examples
- DateDiff Syntax
- Examples of Excel VBA DateDiff Function
- Referencing Dates
- Using Different Units of Interval
DateDiff Description
Returns the difference between two date values, based on the interval specified.
Simple DateDiff Examples
Here is a simple DateDiff example:
Sub DateDiff_Year()
MsgBox DateDiff("yyyy", #1/1/2019#, #8/1/2021#)
End Sub
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.
Sub DateDiff_Year()
MsgBox DateDiff("yyyy", #8/1/2021#, #1/1/2019#)
End Sub
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:
Sub DateDiff_ReferenceDates()
MsgBox DateDiff("m", #4/1/2019#, #8/1/2021#)
MsgBox DateDiff("m", DateSerial(2019, 4, 1), DateSerial(2021, 8, 1))
MsgBox DateDiff("m", DateValue("April 1, 2019"), DateValue("August 1, 2021"))
End Sub
Or you can reference cells containing dates:
Sub DateDiff_ReferenceDates_Cell()
MsgBox DateDiff("m", Range("C2").Value, Range("C3").Value)
End Sub
Or create and reference date variables:
Sub DateDiff_Variable()
Dim dt1 As Date, dt2 As Date
dt1 = #4/1/2019#
dt2 = #8/1/2021#
MsgBox DateDiff("m", dt1, dt2)
End Sub
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!
Learn More
Using Different Units of Interval
Quarters
Sub DateDiff_Quarter()
MsgBox "the number of quarters: " & DateDiff("q", #1/1/2019#, #1/1/2021#)
End Sub
Months
Sub DateDiff_Month()
MsgBox "the number of months: " & DateDiff("m", #1/1/2019#, #1/1/2021#)
End Sub
Days
Sub DateDiff_Day()
MsgBox "the number of days: " & DateDiff("d", #1/1/2019#, #1/1/2021#)
End Sub
Weeks
Sub DateDiff_Week()
MsgBox "the number of weeks: " & DateDiff("w", #1/1/2019#, #1/1/2021#)
End Sub
Hours
Sub DateDiff_Hour()
Dim dt1 As Date
Dim dt2 As Date
Dim nDiff As Long
dt1 = #8/14/2019 9:30:00 AM#
dt2 = #8/14/2019 1:00:00 PM#
nDiff = DateDiff("h", dt1, dt2)
MsgBox "hours: " & nDiff
End Sub
Minutes
Sub DateDiff_Minute()
MsgBox "mins: " & DateDiff("n", #8/14/2019 9:30:00 AM#, #8/14/2019 9:35:00 AM#)
End Sub
Seconds
Sub DateDiff_Second()
MsgBox "secs: " & DateDiff("s", #8/14/2019 9:30:10 AM#, #8/14/2019 9:30:22 AM#)
End Sub
DateDiff function in VBA is an inbuilt function in VBA, categorized under the Date and Time function in VBA. We can use this function to get the difference between two dates. This function takes three arguments. The first argument is what part of the difference we want, which can be years, days or months, or seconds and two dates, and the result is an integer.
Table of contents
- DATEDIFF Function in VBA
- What is the DATEDIFF Function in Excel VBA?
- Examples of DATEDIFF Function in Excel VBA
- Example #1 – To Find Differences in Days
- Example #2 – To Find Difference in Months
- Example #3 – To Find Difference in Years
- Assignment as a Practice
- Recommended Articles
The DateDiff function in VBA calculates the difference between two dates in days, months, quarters, and years.
In Excel, finding the difference between two dates has many ways. You do not need a special formula to calculate the difference between two dates.
For example, look at the below image.
If we want to calculate the difference between these two dates, we can subtract date 1 from date 2.
It has given us the difference between two dates in several days. However, it is a problem with this generic formula. If we need the difference in months, years, quarters, etc., it cannot give.
This article will show you how to use this DateDiff function in VBA.
What is the DATEDIFF Function in Excel VBA?
The Datediff in VBA stands for “Date Difference between two dates.”
This function can give us the number of the time interval between two dates. When we want to find the difference between two dates, we can find it in days, weeks, months, quarters, etc.
To understand the function, look at the below syntax of the function.
Interval: This is nothing but in what way you want to calculate the date difference. The same list is below, whether in days, months, weeks, quarters, etc.
Date 1: What is the first date you want to find the difference?
Date 2: What is the second date you want to find the difference from Date 1?
Here, the formula is Date 2 – Date 1.
[First Day of Week]: What is the first day of the week? We can agree with the following arguments.
[First Week Of the Year]: What is the year’s first week?
[First Week Of the Year]: What is the year’s first week? We can enter the following arguments.
Examples of DATEDIFF Function in Excel VBA
The following are examples of Excel VBA DateDiff.
You can download this VBA DateDiff Function Template here – VBA DateDiff Function Template
Example #1 – To Find Differences in Days
Assume you have two dates, “15-01-2018” and “15-01-2019”. Let’s find all kinds of differences between these two dates.
Step 1: Create a macro name first.
Code:
Sub DateDiff_Example1() End Sub
Step 2: Define Two Variables as Date.
Code:
Sub DateDiff_Example1() Dim Date1 As Date Dim Date2 As Date End Sub
Step 3: Now, for the Date1 variable, assign “15-01-2018,” and for the Date2 variable, assign “15-01-2019.”
Code:
Sub DateDiff_Example1() Dim Date1 As Date Dim Date2 As Date Date1 = "15-01-2018" Date2 = "15-01-2019" End Sub
Step 4: Now, define one more variable, “As Long,” to store results.
Code:
Sub DateDiff_Example1() Dim Date1 As Date Dim Date2 As Date Dim Result As Long Date1 = "15-01-2018" Date2 = "15-01-2019" End Sub
Step 5: Now, assign the value for this variable through the DateDiff function in VBA.
Code:
Sub DateDiff_Example1() Dim Date1 As Date Dim Date2 As Date Dim Result As Long Date1 = "15-01-2018" Date2 = "15-01-2019" Result =DateDiff( End Sub
Step 6: The first argument is what kind of difference we need between these dates. We need to find the number of days, so supply the argument as “D.”
Code:
Sub DateDiff_Example1() Dim Date1 As Date Dim Date2 As Date Dim Result As Long Date1 = "15-01-2018" Date2 = "15-01-2019" Result =DateDiff("D", End Sub
Step 7: What is the first date to find the difference? Our first date is “15-01-2018,” which we have already assigned to the variable “Date1”. So, supply the variable name here.
Code:
Sub DateDiff_Example1() Dim Date1 As Date Dim Date2 As Date Dim Result As Long Date1 = "15-01-2018" Date2 = "15-01-2019" Result =DateDiff("D",Date1, End Sub
Step 8: What is the second date to find the difference? The second date is “15-01-2019,” which holds the value through the variable “Date2.”.
Code:
Sub DateDiff_Example1() Dim Date1 As Date Dim Date2 As Date Dim Result As Long Date1 = "15-01-2018" Date2 = "15-01-2019" Result = DateDiff("D", Date1, Date2) End Sub
Step 9: Ignore the last two parameters. Now, assign the variable “Result” value through the VBA message boxVBA MsgBox function is an output function which displays the generalized message provided by the developer. This statement has no arguments and the personalized messages in this function are written under the double quotes while for the values the variable reference is provided.read more.
Code:
Sub DateDiff_Example1() Dim Date1 As Date Dim Date2 As Date Dim Result As Long Date1 = "15-01-2018" Date2 = "15-01-2019" Result = DateDiff("D", Date1, Date2) MsgBox Result End Sub
Now, run the code using the F5 key or manually. We will get the difference between these two dates in numbers.
So, from “15-01-2018” to “15-01-2019,” the exact difference is one year, so we got 365 days.
Like this, we can find the difference between two dates in time intervals.
Example #2 – To Find Difference in Months
Code:
Sub DateDiff_Example2() Dim Date1 As Date Dim Date2 As Date Dim Result As Long Date1 = "15-01-2018" Date2 = "15-01-2019" Result = DateDiff("M", Date1, Date2) MsgBox Result End Sub
Run this code using the F5 key. You can run it manually to show the result as given below.
Example #3 – To Find Difference in Years
Code:
Sub DateDiff_Example3() Dim Date1 As Date Dim Date2 As Date Dim Result As Long Date1 = "15-01-2018" Date2 = "15-01-2019" Result = DateDiff("YYYY", Date1, Date2) MsgBox Result End Sub
Run this code using the F5 key or manually to see the result.
Assignment as a Practice
We hope you have understood the function of VBA DateDiff. Take a look at the below homework for you. Find the difference between the below dates in “Months.”
If you have not found the way, below is the readymade code.
Code:
Sub Assignment() Dim k As Long For k = 2 To 8 Cells(k, 3).Value = DateDiff("M", Cells(k, 1), Cells(k, 2)) Next k End Sub
You can run this code manually or press the F5 key to see the result.
Recommended Articles
This article is a guide to VBA DateDiff Function. Here we learn how to use DateDiff Function to find differences in days, months, and years in Excel VBA, practical examples, and a downloadable template. Below you can find some useful Excel VBA articles: –
- DATE Function in Excel
- Date Excel Format
- Date Function in VBA
- DateAdd in VBA
- VBA COUNTA
title | keywords | f1_keywords | ms.prod | ms.assetid | ms.date | ms.localizationpriority |
---|---|---|---|---|---|---|
DateDiff function (Visual Basic for Applications) |
vblr6.chm1012950 |
vblr6.chm1012950 |
office |
15c9df5f-1403-b6a5-71b9-611e9820d804 |
12/12/2018 |
high |
Returns a Variant (Long) specifying the number of time intervals between two specified dates.
Syntax
DateDiff(interval, date1, date2, [ firstdayofweek, [ firstweekofyear ]] )
The DateDiff function syntax has these named arguments:
Part | Description |
---|---|
interval | Required. String expression that is the interval of time you use to calculate the difference between date1 and date2. |
date1, date2 | Required; Variant (Date). Two dates you want to use in the calculation. |
firstdayofweek | Optional. A constant that specifies the first day of the week. If not specified, Sunday is assumed. |
firstweekofyear | Optional. A constant that specifies the first week of the year. If not specified, the first week is assumed to be the week in which January 1 occurs. |
Settings
The interval argument has these settings:
Setting | Description |
---|---|
yyyy | Year |
q | Quarter |
m | Month |
y | Day of year |
d | Day |
w | Weekday |
ww | Week |
h | Hour |
n | Minute |
s | Second |
The firstdayofweek argument has these settings:
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 |
The firstweekofyear argument has these settings:
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. |
Remarks
Use the DateDiff function to determine how many specified time intervals exist between two dates. For example, you might use DateDiff to calculate the number of days between two dates, or the number of weeks between today and the end of the year.
To calculate the number of days between date1 and date2, you can use either Day of year («y») or Day («d»). When interval is Weekday («w»), DateDiff returns the number of weeks between the two dates. If date1 falls on a Monday, DateDiff counts the number of Mondays until date2. It counts date2 but not date1.
If interval is Week («ww»), however, the DateDiff function returns the number of calendar weeks between the two dates. It counts the number of Sundays between date1 and date2. DateDiff counts date2 if it falls on a Sunday; but it doesn’t count date1, even if it does fall on a Sunday.
If date1 refers to a later point in time than date2, the DateDiff function returns a negative number. The firstdayofweek argument affects calculations that use the «w» and «ww» interval symbols.
If date1 or date2 is a date literal, the specified year becomes a permanent part of that date. However, if date1 or date2 is enclosed in double quotation marks (» «), and you omit the year, the current year is inserted in your code each time the date1 or date2 expression is evaluated. This makes it possible to write code that can be used in different years.
When comparing December 31 to January 1 of the immediately succeeding year, DateDiff for Year («yyyy») returns 1 even though only a day has elapsed.
[!NOTE]
For date1 and date2, if the Calendar property setting is Gregorian, the supplied date must be Gregorian. If the calendar is Hijri, the supplied date must be Hijri.
Example
This example uses the DateDiff function to display the number of days between a given date and today.
Dim TheDate As Date ' Declare variables. Dim Msg TheDate = InputBox("Enter a date") Msg = "Days from today: " & DateDiff("d", Now, TheDate) MsgBox Msg
See also
- Functions (Visual Basic for Applications)
[!includeSupport and feedback]
Dates | Times
The DateDiff function in Excel VBA can be used to get the number of days, weeks, months or years between two dates. You can also use the DateDiff function to calculate the time difference between two times.
Dates
Place a command button on your worksheet and add the following code lines:
Dim firstDate As Date, secondDate As Date, n As Integer
firstDate = DateValue(«Jan 19, 2020»)
secondDate = DateValue(«Feb 25, 2020»)
n = DateDiff(«d», firstDate, secondDate)
MsgBox n
Explanation: first, we declare two dates. Next, we initialize the two dates using the DateValue function. The DateDiff function has three arguments. Fill in «d» for the first argument to get the number of days between two dates. Finally, we use a MsgBox to display the number of days between the two dates.
Result when you click the command button on the sheet:
Note: use «ww» to get the number of weeks between two dates. Use «m» to get the number of months between two dates. Use «yyyy» to get the number of years between two dates.
Times
Place a command button on your worksheet and add the following code lines:
Dim firstTime As Date, secondTime As Date, x As Integer
firstTime = TimeValue(«2:15:00 pm»)
secondTime = TimeValue(«5:15:00 pm»)
x = DateDiff(«h», firstTime, secondTime)
MsgBox x
Explanation: first, we declare two times (times are declared as dates). Next, we initialize the two times using the TimeValue function. The DateDiff function has three arguments. Fill in «h» for the first argument to calculate the number of hours between two times. Finally, we use a MsgBox to display the number of hours between the two times.
Result when you click the command button on the sheet:
Note: use «n» to calculate the number of minutes between two times. Use «s» to calculate the number of seconds between two times. Place your cursor on DateDiff in the Visual Basic Editor and click F1 for help on the other interval specifiers.