Excel’s DateDif function

Anna was doing some work tonight in one of her spreadsheets and needed a bit of help. One of the things she was doing was calculating the number of months between 2 dates. There isn’t really an easy way to do this in Excel without resorting to using its VBA macro language. Anna found an undocumented function in Excel called “DateDif” (one “f”). Unfortunately, this function is undocumented and will not show up in the list of Date and Time functions.

datedif

Basically, this function takes three parameters:

=DateDif(Date1, Date2, Interval)

where Date1 and Date2 are dates and Interval is the interval type (e.g. “m” for months).

The calculation is simple: Find the DateDif between 2 dates to find the number of months and add 1 to make it inclusive. But the catch is that if the start date is before a minimum start date, ignore the start date and use the minimum start date instead. Likewise, if the end date is after a maximum end date, use the maximum end date instead. Well, this proved unwieldy since our simple one-line function started stretching into something like:

=DateDif(if(Date1<MinDate, MinDate, Date1), if(Date2>MaxDate, MaxDate, Date2), Interval)

Remember, the “if” function takes 3 parameters as well: =if(logical_condition,value_if_true, value_if_false).

What did I do? I decided to write a simple macro instead using good old “ActiveCell.Value” and “ActiveCell.Offset”, etc. There’s a lot going in that function and it’s a lot easier to break things up onto separate lines and step through the code as it executes.

This entry was posted on Friday, March 28th, 2008 at 12:51 am and is filed under Technology. You can follow any responses to this entry through the RSS 2.0 feed. You can leave a response, or trackback from your own site.

No related posts. Try these:

2 Responses to “Excel’s DateDif function”

  1. In regards to your DateDif page, you mention a “minimum start date” and a “maximum end date.” What are these dates and how do they relate to the dates you want to pick as a start and end date for a datedif calculation?

    I would appreciate any insight you may offer.

    Thank you and have a nice day.

  2. Lauren,
    Sorry about the confusion. The “minimum start date” was a business rule that Anna needed to follow. You can pick any date you like to pass in to the DateDif function. In Anna’s case, the date for the first parameter could not be before a certain date. Likewise, the date for the second parameter could not be after a certain date. So, I used an If() expression to choose.

    Hope this helps.
    Vince

Leave a Reply