Development‎ > ‎VBScript‎ > ‎

Find nearest weekday

Folowing code will find a date of the nearest weekday relative to the specified date.

So for example, if today is Tuesday and we are looking for a nearest Monday the function will return yesterday's date.

'*********************************************************************************
'* Function signature: FindNearestWeekday(sDayOfTheWeek, dDate)
'* Description: Function search for the date of the weekday which is nearest to
'*                the date passed as the second parameter.  
'*
'* Parameters
'* sDayOfTheWeek - weekday name (e.g. Monday, Tuesday, Wednesday)
'* dDate - VBScript date 
'*
'* Return Value
'* Date of the weekday which is nearest to the date passed as the dDate parameter
'*********************************************************************************
Function FindNearestWeekday(sDayOfTheWeek, dDate)
    Dim vbDayOfTheWeek

    'Convert Day of the week name into the VBScript constant (e.g. vbMonday...)
    Execute("vbDayOfTheWeek = vb" & sDayOfTheWeek)

    FindNearestWeekday = DateAdd("d", vbDayOfTheWeek-Weekday(dDate,vbMonday)-1, dDate)
End Function

Below is a example on how the function can be used in the script code:

'Declate dateToday variable and initialize it with current date
Dim dateToday
dateToday = Date

'Delare variable for the date of the nearest Monday
Dim dateNearestMonday

'Get the date of the nearest Monday and assign it is dateNearestMonday variable
dateNearestMonday = FindNearestWeekday("Monday", dateToday)

'Display a message with the function result
MsgBox "The date of the nearest Monday is: " & dateNearestMonday

Comments