Reputation: 73
I'm trying to calculate the number of months in a given time range that fall within 2019.
My data looks like this:
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:
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
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:
Formula in D2
:
=SUMPRODUCT((DATE(2019,ROW($1:$12),1)>=A2)*(DATE(2019,ROW($1:$12),1)<=C2))
Upvotes: 1
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
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