How would I create a query/vba function similar to DateDiff that splits the result into days per month (i.e. 1/1/2010 – 2/3/2010 = January: 31, February: 3 (disregarding formatting)).
How would I create a query/vba function similar to DateDiff that splits the result
Share
OK, I think I see what you want to do.
First of all you need a function that returns the number of days in a month, given the month and year (you need to know the year to account for changing number of days in February owing to leap years):
I’ve written a function GetMonthDays that takes the start date and end date and returns an array (1 to 12) of integers, containing the number of days in each month, between the specified start and end dates. The start and end dates can be any number of years apart, it will accumulate the total number of days in each month over a period of multiple years if necessary.
For example, a function call such as:
would return an array [0,0,0,0,0,18,31,1,0,0,0,0]
A call such as:
returns [15,0,0,0,0,0,0,0,0,0,0,7]
Over multiple years, for example:
it would return [46,28,31,30,31,30,31,31,30,31,30,38]
You can see that it has accumulated the number of days across two Januarys (31 + 15) and two Decembers (31 + 7). I’m not 100% sure this is what you want, but it makes sense to me if given a date range spanning more than 12 months.
Basically, the function loops through each month between the start and end dates and accumulates the days in each. The first and last month are special cases where a little calculation is required, otherwise it’s simply the number of days in the month.
The function is as follows, minus error checking:
I’ve been testing it using a function such as:
This should be a good starting point for you at the very least. Good luck!