Function WeeksToSelect(TableName, DateFieldName) As String
'This routine will accept the table name and name of the date field.
'This routine will find the oldest date in the table, in the field named, and then return a string of weeks,
' separated by a semi-colon for all the weeks represented in the dates within the table.
Dim OldestDate As Date
Dim NewestDate As Date
Dim LastMondayUsed As Date
Dim strWeek As String
Dim AllWeeks As Variant
Dim RetVal As Variant 'used as a work variable
[COLOR="Red"]'Change the next line to give this routine a fixed starting Monday
'Suggestion: OldestDate = #Jan 1, 2007# 'or whatever date you choose[/COLOR]
OldestDate = DMin(DateFieldName, TableName)
RetVal = Format(OldestDate, "w", vbMonday) '1 = Monday, 2 = Tuesday, etc.
RetVal = DateAdd("d", RetVal - 1, OldestDate) 'This will get the closest Monday to the oldest date
LastMondayUsed = DateAdd("d", -7, RetVal) 'This gives us a starting point one week before where we want to start.
NewestDate = DMax(DateFieldName, TableName)
'All initial values have been calculated.
'Now, loop through this code building the list of weeks to be returned to the caller. This string will then
' be placed into the RowSource of the combo box by the caller.
AllWeeks = Null 'Set to null for later
While LastMondayUsed <= NewestDate
'Now, we will calculate the next week days to return as one week for the combo box
LastMondayUsed = DateAdd("d", 7, LastMondayUsed) 'This will give us the Monday date for the current week
'If the new LastMondayUsed is larger than the NewestDate in the table, return an empty string ("") to
' signify we have reached the end of the line.
strWeek = Format(LastMondayUsed, "mm/dd/yyyy") 'Put the Monday date into the work string
'The next line will build the Week to be returned to the caller of this function
' By adding [COLOR="Red"]6[/COLOR] to the Monday date we get the [COLOR="Red"]Sunday[/COLOR] date for the complete week
strWeek = strWeek & " - " & Format(DateAdd("d", [COLOR="Red"]6[/COLOR], LastMondayUsed))
AllWeeks = AllWeeks + ";" & strWeek
Wend
WeeksToSelect = AllWeeks
End Function