DateDiff Function


The DateDiff function in Excel VBA can be used to get the number of days between two 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("Jun 19, 2010")
secondDate = DateValue("Jul 25, 2010")

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 since we want 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:

Days between two Dates in Excel VBA

Change "d" to "ww" to get the number of weeks between two dates. Place your cursor on DateDiff in the Visual Basic Editor and click F1 for help on the other interval specifiers.

3/8 Completed! Learn more about dates and times >
Back to Top: DateDiff Function   |   Go to Next Chapter: Events