I am trying to create a script that gets the count of Business days, Calendar days and Weekdays within a set period (23rd of Previous month and 23rd of Current month).
I have the following script where I tried to use Worksheet Functions but it doesn't work, I get
"Object variable or With block variable not set"
error, what gives?
Sub DayCounts()
Dim cYear As String
Dim pMon As String
Dim cpMon As String
Dim start_date As String
Dim end_date As String
Dim mySh As Worksheet
Dim wf As WorksheetFunction
Set mySh = Sheets("prod_log_manual")
cYear = Format(Date, yyyy) 'get year
pMon = Format(Date - 1, mm) 'get previous month
cMon = Format(Date, mm) 'get current month
start_date = cYear & pMon & 24 '23th of previous month
end_date = cYear & cMon & 23 '23rd of current month
mySh.Range("P7") = wf.NetworkDays(start_date, end_date) 'get number of workdays in period
mySh.Range("P8") = wf.Day(start_date, end_date) 'get number of calendar days in period
mySh.Range("P9") = mySh.Range("P8").Value / 7 'get number of weeks within period
End Sub
First, correct the date collection per Vityata's response.
You might want to use actual dates, not string concatenations.
mySh.Range("P7") = wf.NetworkDays(dateserial(clng(cYear)+cbool(clng(pmon)=12), clng(pmon), 24), dateserial(clng(cYear), clng(cmon), 23)) 'get number of workdays in period
NetworkDays is inclusive. Should you be using 23 for both? Shouldn't the previous be 24 or the current be 22?