Get the week number from a date

Just a simple function to get the week number from a date.

Function GetWeekNr(InputDate As Long) As String
    Dim intWeekday As Integer, intYear As Integer, lngDateSerial As Long, intWeeks As Integer
    Dim strWeekNr As String
    
    On Error GoTo ErrFunction
    
    GetWeekNr = "0"
    conv = 0
    strWeekNr = ""
    
    If InputDate < 1 Then Exit Function
    intWeekday = Weekday(InputDate, vbSunday)
    intYear = Year(InputDate + ((8 - intWeekday) Mod 7) - 3)
    lngDateSerial = DateSerial(intYear, 1, 1)
    intWeeks = (Weekday(lngDateSerial, vbSunday) + 1) Mod 7
    conv = Int((InputDate - lngDateSerial - 3 + intWeeks) / 7) + 1
    strWeekNr = Format(CStr(conv), "00")
    
ExitFunction:
    GetWeekNr = strWeekNr
    Exit Function
ErrFunction:
    strWeekNr = "0"
    GoTo ExitFunction
End Function

Leave a Reply