Saturday, July 23, 2011

Appointments - creating recurring events using VB

        We want to have an event occur every other week.  How do we know if the event is supposed to occur in a given week?
      
Here's a cool little bit of code, using an arithmetical operator you don't see very often "MOD" 

The Mod operator returns the remainder of a division. Its an easy way to see if one number is divisible by another.  Do you want to know if 144 is divisible by 12?  144 Mod 12 returns 0, because there is no remainder. 12 x 12 = 144.   So, 5 Mod 2 is equal to 1,  because 2 goes into 5 two times, with 1 left over.   

For our purposes, we take our current date and subtract the beginning date to find out how many weeks have gone by.  Lets say 6 weeks have gone by.  If our event is set to happen every other week from the starting week, then our event should happen this week, right?  But how do we determine that in the program?

        startDate = #7/23/2011#
        endDate = #9/1/2011#

        myDiff = DateDiff("ww", startDate, endDate) ' subtract the startDate from the endDate to find out how many weeks have gone by

(The "ww" in the DateDiff function tells the program to subtract the number of weeks from  startDate to endDate. In this case, 6 weeks have gone by.)

       remainder = myDiff  Mod 2 ' check to see if this is divisible by 2?
       if remainder = 0 then ' yes 6 is divisible by 2, so our event will occur this week.
            '
            ' do some stuff
            ' 
       end if


Nifty, eh?