计算上个月的最后一个工作日

时间:2021-05-10 12:08:48

标签: excel vba

大家好,请问上个月的最后一个工作日(仅周末除外)的 VBA 代码可以帮我吗?

我在下面尝试的一个是只给我最后日期而不是工作日。

Range("B8") = Application.WorksheetFunction.EoMonth(Now, -1)

2 个答案:

答案 0 :(得分:2)

怎么样:

Sub marine()
    Dim dt As Date, dt_LastMonth As Date, dt_LastWorkingDate_LastMonth As Date
    Dim wf As WorksheetFunction
    
    Set wf = Application.WorksheetFunction
    
    dt = Now
    dt_LastMonth = DateSerial(Year(dt), Month(dt) - 1, 1)
    dt_LastWorkingDate_LastMonth = wf.WorkDay(wf.EoMonth(dt_LastMonth, 0) + 1, -1)
    MsgBox dt_LastWorkingDate_LastMonth
End Sub

如果今天是 2021 年 5 月的某一天,则代码生成:

enter image description here

答案 1 :(得分:0)

这是一个返回上个月最后一个工作日的简单函数。

Private Function LastWorkday() As Date

    Dim Fun     As Date             ' function return value
    
    Fun = DateSerial(Year(Date), Month(Date), 0)
    Do
        If (Weekday(Fun) < vbSaturday) And _
           (Weekday(Fun) > vbSunday) Then Exit Do
        Fun = Fun - 1
    Loop
    LastWorkday = Fun
    
    Debug.Print Format(Fun, "ddd, d mmm yyyy")
End Function