AmyV
AmyV

Reputation: 73

Excel | nested IF statements using dates

I'm trying to calculate the number of months in a given time range that fall within 2019.

My data looks like this:

enter image description here

I changed the format of my Start Date and End Date columns to "date". The "Duration in months" and output column have number formatting.

I approached it as follows:

  1. If Start Date (year) < 2019 AND End date (year) = 2019, take the number of months between 1-1-2019 and the end date.
  2. If start Date (year) < 2019 AND End date (year) > 2019, the number of months in 2019 = 12
  3. If start Date (year) = 2019 AND End date (year) = 2019, take the number of months between Start Date and End date.
  4. If start Date (year) = 2019 AND End date (year) > 2019, take the number of months between Start Date and 1-1-2020.
  5. For all other cases, the number of months = 0.

I then followed the instructions from this website for nested IF functions.

I came up with the following formula: (Edit: changed last datedif to 2020 instead of 2019)

=IF(AND(YEAR(A3)<2019;YEAR(C3)=2019);DATEDIF(DATE(2019;1;1);C3;"m");IF(AND(YEAR(A3)<2019;YEAR(C3)>2019);12;IF(AND(YEAR(A3)=2019;YEAR(C3)=2019);DATEDIF(A3;C3;"m");IF(AND(YEAR(A3)=2019;YEAR(C3)>2019); DATEDIF(A3;DATE(2020;1;1);m);0))))

For the first 4 rows, it correctly returns 12. For row 7 and 8, however, it returns #NAME? .

No matter what I try, I can't seem to get it to work. Any ideas on how I can solve this?

Much appreciated!

Amy

Upvotes: 1

Views: 7308

Answers (3)

JvdV
JvdV

Reputation: 75840

Alternatively, the following will give you the amount of full months between two dates. This works with your sample where your dates start on the first day of a month:

enter image description here

Formula in D2:

=SUMPRODUCT((DATE(2019,ROW($1:$12),1)>=A2)*(DATE(2019,ROW($1:$12),1)<=C2))

Upvotes: 1

Plutian
Plutian

Reputation: 2309

For the entire formula you have been consistent, apart from the last IF statement, where you went wrong within your DATEDIF( statement:

DATEDIF(A3;DATE(2019;1;1);m);0)

First of all you forgot to put m in quotes: "m"

Secondly you accidentally swapped the Date and Cell references, so it would have resolved #NUM. The full correct formula should be:

=IF(AND(YEAR(A7)<2019;YEAR(C7)=2019);DATEDIF(DATE(2019;1;1);C7;"m");IF(AND(YEAR(A7)<2019;YEAR(C7)>2019);12;IF(AND(YEAR(A7)=2019;YEAR(C7)=2019);DATEDIF(A7;C7;"m");IF(AND(YEAR(A7)=2019;YEAR(C7)>2019);DATEDIF(DATE(2019;1;1);A7;"m");0))))

Which will give you the result 4.

Upvotes: 2

Tom Sharpe
Tom Sharpe

Reputation: 34180

You've missed the quotes round the final "m" - try

=IF(AND(YEAR(A3)<2019;YEAR(C3)=2019);DATEDIF(DATE(2019;1;1);C3;"m");IF(AND(YEAR(A3)<2019;YEAR(C3)>2019);12;IF(AND(YEAR(A3)=2019;YEAR(C3)=2019);DATEDIF(A3;C3;"m");IF(AND(YEAR(A3)=2019;YEAR(C3)>2019); DATEDIF(A3;DATE(2019;1;1);"m");0))))

Upvotes: 0

Related Questions