Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations strongm on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

days in the week

Status
Not open for further replies.

mikeba1

Programmer
Jan 2, 2005
235
GB
Does anyone have a routine to calculate the number of Thursdays(or any other day) between two dates.
thanks
 
Here is a function that should do what you ask;

Code:
'---------------------------------------------------------------------------------------
' Procedure : finddays
' Author    : mellon
' Date      : 21-Aug-2016
' Purpose   : This routine will return a count of the number of selected weekday (EG Thursdays)
' bewteen 2 dates.
'
'parameters:
'
'Date1 ----the starting date of the time interval
'Date2 ---- the endinig date of the time interval
'WhichDay-- integer representing a Day where 1=Sun,2=Mon,3=Tue,4=Wed,5=Thur,6=Fri,7=Sat
'Showdebug --if True will display the dates that are Whichday between Date1 and Date2
'             in the immediate window
'---------------------------------------------------------------------------------------
'
Function finddays(StartDate As Date, enddate As Date, WhichDay As Integer, _
                  Optional Showdebug = False) As Integer

    Dim tmpDate As Date
    Dim NumDaysChosen As Integer
10        On Error GoTo finddays_Error

20    tmpDate = StartDate
30        Do While tmpDate <= enddate
40      tmpDate = tmpDate + 1
50      If WeekDay(tmpDate) = WhichDay Then
60          If Showdebug Then Debug.Print tmpDate
70          NumDaysChosen = NumDaysChosen + 1
80      Else
90      End If
100     i = i + 1
110       Loop
120       finddays = NumDaysChosen

130       On Error GoTo 0
140       Exit Function

finddays_Error:

150       MsgBox "Error " & err.number & " in line " & Erl & " (" & err.Description & ") in procedure finddays of Module DateCalcs_UA"
End Function

Test routine using 7 (Saturday)
Code:
Sub testDindDays()
Dim date1 As Date: date1 = #2/23/2016#
Dim date2 As Date: date2 = #10/27/2016#
Dim dayChosen As Integer: dayChosen = 7 'where Sun = 1, Mon = 2......Sat = 7
Dim TotDays As Integer
TotDays = finddays(date1, date2, dayChosen, True)
Debug.Print "Number of Saturdays between " & date1 & " and " & date2 & " is " & TotDays
End Sub
 
Or the slightly shorter:

Code:
[blue]Public Function GetSpecificDayCount(StartDate As Date, EndDate As Date, SpecificDay As VbDayOfWeek) As Long
    GetSpecificDayCount = DateDiff("ww", StartDate, EndDate, SpecificDay)
End Function[/blue]
 
Thanks chaps.
Sorted by loops and datediff functions
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top