You can add a final twist to the ChatGPT solution:
Code:
Public Function DateNearestWeekday( _
ByVal BaseDate As Date, _
ByVal DayOfWeek As VbDayOfWeek, _
Optional ByVal Bias As Integer) _
As Date
Dim BaseWeekday As VbDayOfWeek
Dim OffsetMajor As Integer
Dim OffsetMinor As Integer
Dim Offset As Integer
Dim WeekdayDate As Date
' The weekday of the base date.
BaseWeekday = Weekday(BaseDate)
' Calculate the day count from the base date to the previous and the following weekday.
OffsetMinor = (BaseWeekday - DayOfWeek + 7) Mod 7
OffsetMajor = (DayOfWeek - BaseWeekday + 7) Mod 7
If OffsetMajor = OffsetMinor Then
Offset = Sgn(Bias) * 7
ElseIf OffsetMajor < OffsetMinor Then
Offset = OffsetMajor
ElseIf OffsetMajor > OffsetMinor Then
Offset = -OffsetMinor
End If
WeekdayDate = DateAdd("d", Offset, BaseDate)
DateNearestWeekday = WeekdayDate
End Function
This will allow you to specify what to do, if the searched weekday is that of the date to search from:
Code:
' If the weekday is that of the base date, argument Bias may be specified:
'
' Bias = 0: The base date (default)
' Bias > 0: The next date of weekday
' Bias < 0: The previous date of weekday