View Single Post
  #3   Report Post  
Posted to microsoft.public.excel.programming
Myrna Larson Myrna Larson is offline
external usenet poster
 
Posts: 863
Default Excel dates seem to confuse me ...

I've attached code for the ISO weeknumber below. For the date range
end-of-1900 through 1st week in 2201, all weeks have 7 days. But there's a
hitch.... the ISO standard says that weeks begin on *Monday*, not Sunday.

Here's an excerpt from the ISO definition: "Week 01 of a year is per
definition the first week that has the Thursday in this year, which is
equivalent to the week that contains the fourth day of January. In other
words, the first week of a new year is the week that has the majority of its
days in the new year. Week 01 might also contain days from the previous year
and the week before week 01 of a year is the last week (52 or 53) of the
previous year even if it contains days from the new year. A week starts with
Monday (day 1) and ends with Sunday (day 7)."

Here's my code for the ISO week number. As far as starting the week on Sunday,
I *think* it requires only that you change vbMonday to vbSunday in the
ISOYearStart routine, but I haven't tested this.

As you can see from this code, the problem resolves to determining the day on
which Week1 begins. Once you have that, you get the week number by N =
(TheDate - YearStart) \ 7 + 1

Function ISOWeekNum(TheDate As Date, Optional NumFormat As Long = 1) As Long
Dim y As Long
Dim YearStart As Date
Dim NextYearStart As Date
Dim N As Long

y = Year(TheDate)
YearStart = ISOYearStart(y)

NextYearStart = ISOYearStart(y + 1)
If TheDate = NextYearStart Then
y = y + 1
YearStart = NextYearStart

ElseIf TheDate < YearStart Then
y = y - 1
YearStart = ISOYearStart(y)
End If

N = (TheDate - YearStart) \ 7 + 1

Select Case NumFormat
Case 1: ISOWeekNum = N
Case 2: ISOWeekNum = (y Mod 100) * 100 + N
Case 3: ISOWeekNum = y * 100 + N
End Select
End Function

Function ISOYearStart(TheYear As Long) As Date
Dim Jan4 As Date

Jan4 = DateSerial(TheYear, 1, 4)
ISOYearStart = Jan4 - Weekday(Jan4, vbMonday) + 1

End Function