for simplicitys' sake instead of "january" "february" etc in C1:N1 I have put just numbers (1-12)
I assume here the YEAR of BOTH the start and finish dates is the same (more coding if not, but you only mentioned 12 month columns...)
I also assume that we are working on start date in A2 and finish date in B2.
Formula for C2:
=IF(AND(MONTH($A2)=C1,MONTH($B2)=C1),$B2-$A2,
IF(MONTH($A2)=C1,1+EOMONTH($A2,0)-$A2,
IF(MONTH($B2)=C1,$B2-DATE(YEAR($B2),C1,1),
IF(AND(MONTH($A2)<C1,MONTH($B2)>C1),DAYSINMONTH(DATE(YEAR($A2),C1,1))
,0))))
copy / drag to D2:N2
explanation:
- if the start and finish dates are in the same month, just calculate the difference, use that in the column where month number matches.
- now we know start and finish months are not the same. if the start month = reference month, then number of days will be calculated by
last_day_of_month - start date
(+1 for the first night)
- now we know the start and finish months are not the same, and reference month is not the start month. If the reference month is the final month, than the number of days will be
final_date - first_day_of_month
- if none of the above then the reference month is either wholly within our date range or outside of it. If start_month < reference month < final_month then days = all days in that month (of the correct year)