获取上周一周五的日期

时间:2017-04-19 16:29:22

标签: excel vba excel-vba date weekday

我试图实施this SO answer以获取上周一周一至周五的日期,并进行测试:

Public Sub listPreviousWeekDays()

Dim dayCtr As Long

For dayCtr = 2 To 6
    Debug.Print DateAdd("ww", -1, Now - (Weekday(Now, dayCtr) - 1))
Next

End Sub

然而,这给出了:

4/10/2017 9:27:18 AM 
4/11/2017 9:27:18 AM 
4/12/2017 9:27:18 AM 
4/6/2017 9:27:18 AM 
4/7/2017 9:27:18 AM 

我的目标是让它回归:

4/10/2017 9:27:18 AM 
4/11/2017 9:27:18 AM 
4/12/2017 9:27:18 AM 
4/13/2017 9:27:18 AM 
4/14/2017 9:27:18 AM 

编辑:为了避免使用XY problem,我会解释我尝试做的事情:我想要运行一个宏,该宏填充前一周的一小部分单元格'周一至周五约会。

2 个答案:

答案 0 :(得分:1)

更新

正如OP指出的那样,当起始日期是星期日时,链接的代码不适用于这个特定的用例。这是一个修复:

Option Explicit   ' always always always use this

Public Function MondayLastWeek(pdat As Date) As Date
    Dim weekday_increment As Long
    weekday_increment = weekday(pdat, vbMonday) - 1
    MondayLastWeek = DateAdd("ww", IIf(weekday_increment = 6, 0, -1), pdat - weekday_increment)
    ' IIf: if we're on Sunday, pdat-weekday_increment is already the date we want.
End Function

Public Sub listPreviousWeekDays()
    Dim monday As Date
    monday = MondayLastWeek(Now)

    Dim dayCtr As Long
    For dayCtr = 0 To 4
        Debug.Print monday + dayCtr
    Next
End Sub

原始答案

这对我有用:

Public Sub listPreviousWeekDays()

    ' First, get last week's Monday just as in the linked question    
    Dim LastMonday As Date
    LastMonday = DateAdd("ww", -1, Now - (Weekday(Now, vbMonday) - 1))

    ' Then, loop over the rest of the week.
    ' Monday + 0 days => Monday
    ' Monday + 4 days => Friday
    Dim dayCtr As Long
    For dayCtr = 0 To 4
        Debug.Print LastMonday + dayCtr
    Next

End Sub

输出:

4/10/2017 12:38:17 PM 
4/11/2017 12:38:17 PM 
4/12/2017 12:38:17 PM 
4/13/2017 12:38:17 PM 
4/14/2017 12:38:17 PM 

我认为问题是Weekday的第二个参数未指定您想要哪一天。相反,它指定一周中的哪一天工作日编号1 some documentation)。不要弄乱Weekday,只需使用linked answer获取星期一,然后根据需要添加天数。

答案 1 :(得分:1)

这应解决问题。

Public Sub listPreviousWeekDays()

Dim dayCtr As Long
For dayCtr = 2 To 6
Debug.Print DateAdd("ww", -1, Now - (Weekday(Now, vbUseSystemDayOfWeek)) + dayCtr)
Next

End Sub