May 23, 2016

Using DatedDif Function in Excel VBA

We can calculate the difference between two date values like difference in years, months, days, quarters, weeks, hours, minutes and seconds. This can be useful in a variety of situations like inventory management. Here we might wish to know how many months or days an item was on the shelf before being sold.

Watch the training video below:

Watch this video on YouTube.

Here’s the complete VBA code to automate the difference calculations between two date values:

Sub dateDifference()
Cells(2, 3) = DateDiff(“yyyy”, Cells(2, 1), Cells(2, 2))
Cells(2, 4) = DateDiff(“m”, Cells(2, 1), Cells(2, 2))
Cells(2, 5) = DateDiff(“d”, Cells(2, 1), Cells(2, 2))
Cells(2, 9) = DateDiff(“q”, Cells(2, 1), Cells(2, 2))
Cells(2, 10) = DateDiff(“w”, Cells(2, 1), Cells(2, 2))
Cells(2, 11) = DateDiff(“h”, Cells(2, 1), Cells(2, 2))
Cells(2, 12) = DateDiff(“n”, Cells(2, 1), Cells(2, 2))
Cells(2, 13) = DateDiff(“s”, Cells(2, 1), Cells(2, 2))
End Sub
Further reading:

Excel 2013 Power Programming with VBA