R
RobV
The code snippet below determines the number of days in a month. I thought
others might find it useful. An explanation of the code follows the snippet.
Dim TargetMonth as Date
Dim NumOfDays as Long
TargetDate = CDate("Feb 2008") 'Date format is flexible
NumOfDays = Day(Dateserial(Year(TargetDate),Month(TargetDate)+1,0))
Explanation
First, the syntax of Dateserial is Dateserial(Year,Month,Day). Second,
starting with the end of the snippet and working backwards: the day is 0.
What is Day 0? It is the day before Day 1 of a month, i.e., the last day of
the previous month. The month is picked out of the TargetDate, e.g., Feb.
Because of what was just said about the day, we need to advance the month by
one from what is stated in the target date. In the example, we add one month
to Feb to get Mar. Day 0 then becomes the last day of the preceding month,
i.e., Feb: either 28 or 29, depending on leap year. The Year resolves that
ambiguity. It identified the Year in the TargetDate. In the example, that
is 2008. So, Dateserial returns the date: "2008 Feb 29". The Day operator
then returns the numeric equivalent of the day in the date, i.e., 29. That's
the number of days in the month.
For me, the snippet has replaced the loops and Case statements that I
previously used to determine the number of days in a month. I hope it does
the same for you.
others might find it useful. An explanation of the code follows the snippet.
Dim TargetMonth as Date
Dim NumOfDays as Long
TargetDate = CDate("Feb 2008") 'Date format is flexible
NumOfDays = Day(Dateserial(Year(TargetDate),Month(TargetDate)+1,0))
Explanation
First, the syntax of Dateserial is Dateserial(Year,Month,Day). Second,
starting with the end of the snippet and working backwards: the day is 0.
What is Day 0? It is the day before Day 1 of a month, i.e., the last day of
the previous month. The month is picked out of the TargetDate, e.g., Feb.
Because of what was just said about the day, we need to advance the month by
one from what is stated in the target date. In the example, we add one month
to Feb to get Mar. Day 0 then becomes the last day of the preceding month,
i.e., Feb: either 28 or 29, depending on leap year. The Year resolves that
ambiguity. It identified the Year in the TargetDate. In the example, that
is 2008. So, Dateserial returns the date: "2008 Feb 29". The Day operator
then returns the numeric equivalent of the day in the date, i.e., 29. That's
the number of days in the month.
For me, the snippet has replaced the loops and Case statements that I
previously used to determine the number of days in a month. I hope it does
the same for you.