A Quicker “Next/Previous Weekday”

In the latest tips supplement [“101 Tech Tips for VB Developers,” Supplement to the February 1998 issue of VBPJ], I noticed a tip titled “Determine Next/Previous Weekday.” This code is shorter and accomplishes the same task with no DLL calls:

 Public Function SpecificWeekday(ByVal D As Date, Optional _	ByVal WhatDay As VbDayOfWeek = vbSaturday, _	Optional GetNext As Boolean = True) As Date 	SpecificWeekday = (((D - WhatDay + GetNext)  7) - _		GetNext) * 7 + WhatDayEnd Function

This code averages about 10 times faster in VB3 and up to 30 times faster in VB5. It works because VB keeps dates internally as the number of days since Saturday, December 30, 1899. A date of 1 represents Sunday, December 31, 1899, which is also its own weekday. This means the WeekDay function is equivalent to the expression (Date – 1) Mod 7 + 1. This is coded for VB5, but by altering the way the Optional parameters are handled, you can make it work in either VB3 or VB4.

Share the Post:
Share on facebook
Share on twitter
Share on linkedin

Overview

Recent Articles: