Excel VBA - 如何在公共假日期间阻止宏工作

时间:2017-04-25 06:13:03

标签: excel-vba vba excel

我目前正面临一个问题,即我需要宏从周一到周六运行,不包括公众假期,因为在PH期间没有报告发送。以下是我的代码:

Sub schedule()
If Weekday(Date, vbMonday) < 6 Then
        Application.OnTime TimeValue("11:00:00"), "broadcast"
        Application.OnTime TimeValue("12:00:00"), "broadcast"
        Application.OnTime TimeValue("13:00:00"), "broadcast"
        Application.OnTime TimeValue("14:00:00"), "broadcast"
        Application.OnTime TimeValue("15:00:00"), "broadcast"
        Application.OnTime TimeValue("16:00:00"), "broadcast"
        Application.OnTime TimeValue("17:00:00"), "broadcast"
        Application.OnTime TimeValue("18:00:00"), "broadcast"
        Application.OnTime TimeValue("19:00:00"), "broadcast"
End If
If Weekday(Date, vbMonday) = 6 Then
        Application.OnTime TimeValue("20:00:00"), "broadcast"
End If

End Sub

提前致谢

1 个答案:

答案 0 :(得分:2)

在日程安排开始时实施类似的内容

Dim arrHolidays As Variant, iDay As Variant
arrHolidays = Array(DateSerial(2017, 4, 25), DateSerial(2017, 4, 26)) 'Add all your holidays here

For Each iDay In arrHolidays
    If Date = iDay Then Exit Sub 'exit this sub if date is a holiday
Next

或者代替for / each循环,你可以使用VBA.Filter(正如@RobinMackenzie所指出的那样)。

Dim arrHolidays As Variant, iDay As Variant
arrHolidays = Array(DateSerial(2017, 4, 25), DateSerial(2017, 4, 26)) 'Add all your holidays here

If UBound(VBA.Filter(arrHolidays, Date)) >= 0 Then Exit Sub

需要在arrHolidays中指定所有假期。如果Date是假期,那么它将取消执行并Exit Sub

从工作表加载假期日期&#34;假期&#34;列A使用

arrHolidays = Application.Transpose(Worksheets("Holidays").Range("A:A").Value)

注意:我们需要在此转置以获得该范围之外的一维数组。