Search code examples
vbadateweekday

Find first Monday of given month or last Monday of previous month


If the first day of the month is Monday to Wednesday the first Monday is that current week.

If the first day is Thursday to Sunday the first Monday is the following Monday.

Examples:

August 2021 - the first Monday would be 02/08/2021 as the first day of the month is Sunday (i.e. after Wednesday).

September 2021 - the first Monday would be 30/08/2021 as the first day of the month is Wednesday.

October 2021 - the first Monday would be 04/10/2021 as the first day of the month is a Friday.

The following code gives the first Monday of the month.

Public Function FirstMonday(myDate As Date) As Date
    Dim d As Date, w As Long
    d = DateSerial(Year(myDate), month(myDate), 1)
    w = Weekday(d, vbMonday)
    FirstMonday = d + IIf(w <> 1, 8 - w, 0)
End Function

Solution

  • You were close. For your test dates, this gave me the expected response:

    Public Function FirstMonday(myDate As Date) As Date
       Dim d As Date, w As Long
       d = DateSerial(Year(myDate), Month(myDate), 1)
       w = Weekday(d, vbMonday)
    
       If w > 3 Then
           FirstMonday = d + (8 - w)
       Else
           FirstMonday = d - w + 1
       End If
    
    End Function
    

    When w > 3, the first day of a month is Thursday to Sunday. In that case, add the days missing to the following Monday (8 - w). Else, go backwards and substract w - 1 to get to the previous week's Monday.