Search code examples
excelvbadateweek-number

Get the number of the week of the month from a given date


I have a set of dates from which I must obtain the week of the month.

There is a lot of literature on how to obtain the week of the year using VBA code but not the week number of the month.

For instance 03-Mar-13 would give week 1 of March, instead I end up with a result of week 10.


Solution

  • This isn't the most elegant code, but it worked for me.

    Some assumptions:

    1. This is a UDF and can be used on a spreadsheet or in code
    2. Weeks start on Sundays
    3. Week 1 can be incomplete week

    =====

    Function WeekOfMonth(selDate As Date)
        Dim DayOfFirst As Integer
        Dim StartOfWeek2 As Integer
        Dim weekNum As Integer
    
        DayOfFirst = Weekday(DateSerial(Year(selDate), Month(selDate), 1), vbSunday)
        StartOfWeek2 = (7 - DayOfFirst) + 2
    
        Select Case selDate
            Case DateSerial(Year(selDate), Month(selDate), 1) _
            To DateSerial(Year(selDate), Month(selDate), StartOfWeek2 - 1)
                weekNum = 1
    
            Case DateSerial(Year(selDate), Month(selDate), StartOfWeek2) _
            To DateSerial(Year(selDate), Month(selDate), StartOfWeek2 + 6)
                weekNum = 2
    
            Case DateSerial(Year(selDate), Month(selDate), StartOfWeek2 + 7) _
            To DateSerial(Year(selDate), Month(selDate), StartOfWeek2 + 13)
                weekNum = 3
    
            Case DateSerial(Year(selDate), Month(selDate), StartOfWeek2 + 14) _
            To DateSerial(Year(selDate), Month(selDate), StartOfWeek2 + 20)
                weekNum = 4
    
            Case DateSerial(Year(selDate), Month(selDate), StartOfWeek2 + 21) _
            To DateSerial(Year(selDate), Month(selDate), StartOfWeek2 + 27)
                weekNum = 5
    
            Case DateSerial(Year(selDate), Month(selDate), StartOfWeek2 + 28) _
            To DateSerial(Year(selDate), Month(selDate) + 1, 1)
                weekNum = 6
        End Select
    
        WeekOfMonth = weekNum
    End Function