| Excel DateDiff Function |
|
Excel DateDiff Function
The DateDiff Excel function is used to calculate the number of frequencies between two dates such as weeks, quarters, years, days etc.
The Basics:
DateDiff(interval, date1, date2, firstdayofweek, firstweekofyear)
Interval = What interval you want to use such as ‘yyyy’ for year, ‘ww’ for weeks etc.
Date1 = The first date
Date2 = The second date
Firstdayofweek = What day is considered the first day of the week. The value is optional and the default value is set at Sunday
Firstweekofyear = You can define the first week based on what you require. For example the default value for the first week is the week in which Jan 1 appears.
Now let’s look at an example. Let’s assume we want to calculate the frequency intervals between two dates based on weeks, days and quarters.
Code
Dim Date1 As Date 'Variable to hold the date value
Dim Date2 As Date 'Variable to hold the date value
Date1 = ActiveSheet.Cells(2, 1).Value 'Assign the value of our first date to the Date1 variable
Date2 = ActiveSheet.Cells(4, 1).Value 'Assign the value of our second date to the Date2 variable
'Now let's add a year ActiveSheet.Cells(8, 1).Value = DateDiff("ww", Date1, Date2)
'Subtract a week ActiveSheet.Cells(10, 1).Value = DateDiff("d", Date1, Date2)
'Now let's add a year ActiveSheet.Cells(12, 1).Value = DateDiff("q", Date1, Date2)
Output
|