Monday, August 10, 2020

VBA Excel How to Get the nearest Monday of a date

Function GetMonday(strDate As String) As Date
    ''get the nearest Monday before the given date
    Dim wkNum As Integer
    Dim dNearestMonday As Date
    wkNum = Weekday(strDate, vbMonday)
    
    Select Case wkNum
        Case 1:
            dNearestMonday = DateValue(strDate)
        Case 2:
            dNearestMonday = DateValue(strDate) - 1
        Case 3:
            dNearestMonday = DateValue(strDate) - 2
        Case 4:
            dNearestMonday = DateValue(strDate) - 3
        Case 5:
            dNearestMonday = DateValue(strDate) - 4
        Case 6:
            dNearestMonday = DateValue(strDate) - 5
        Case 7:
            dNearestMonday = DateValue(strDate) - 6
        Case Else
            dNearestMonday = #1/1/1900#
    End Select
    GetMonday = dNearestMonday
End Function

No comments:

Post a Comment

Hot Topics