Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Workday Function to add Workdays

I'm trying to run code based off of dates in the D column. The code below works. But the "if" part of the conditional formatting needs to be + 30 workdays, not plus thirty days. I'm assuming that the WORKDAY function helps with this. But when I try + workday(30) and things like that, I don't get anywhere.

For Each oKey In oDictionary.keys
    Editing_Sheet.Range("A1").CurrentRegion.AutoFilter Field:=1,    Criteria1:=CStr(oKey)
    LastRowFiltered = Editing_Sheet.Cells(Rows.Count, "A").End(xlUp).Row
        If Range("D" & LastRowFiltered) <= Date + 30 Then
         'run code'
like image 820
New2VBA Avatar asked Dec 06 '25 03:12

New2VBA


2 Answers

To use the worksheet Workday() function within VBA:

Sub WhyWork()
    Dim d1 As Date, wf As WorksheetFunction
    Set wf = Application.WorksheetFunction
    d2 = wf.WorkDay(Date, 30)
    MsgBox Date & vbCrLf & d2
End Sub
like image 51
Gary's Student Avatar answered Dec 08 '25 20:12

Gary's Student


To build on @Gary's Student's answer, here's an example written as a VBA function, returning the calculated date. So, if you want to feed it a date and get one back, or need to loop through an array or range of cells, might be useful.

'Workday Function via VBA
Function WorkDayCalc(ByVal d1 As Date, ByVal days As Integer) As Date
    Dim wf As WorksheetFunction
    Set wf = Application.WorksheetFunction
    WorkDayCalc = wf.WorkDay(d1, days)
End Function

'Example Usage
Sub Test_WorkDayCalc()
    Dim d As Date, i As Integer
    d = CDate("01/03/2022")
    i = 30
    MsgBox "Start " + CStr(d) & vbCrLf & "End  " + CStr(WorkDayCalc(d, i))
End Sub
like image 36
Daniel Avatar answered Dec 08 '25 19:12

Daniel