在if函数中添加Workday

如果时间在下午5点10分到8点15分之间,我有一个如果运行函数的条件。

我怎么能添加另一个条件,说只有在一个工作日,如果时间是下午5点10分至8点15分。

请参阅下面的代码:

If Format(Time, "hhmm") > 1710 And Format(Time, "hhmm") < 2015 Then Do stuff Else Stop End If 

我想避免在周末和银行假期运行代码。

非常感谢

用实际的时间值来处理你的时间,而不是用TimeSerial函数看起来像时间值的string。 使用Weekday函数来确定周一至周五的数值。

 If Time >= TimeSerial(17, 10, 0) And Time <= TimeSerial(20, 15, 0) And Weekday(Date, 2) <6 Then Do stuff Else Stop End If 

在@ Zaider的链接中使用IsWeekendfunction。 就像@Forward Ed所说,你需要一个银行假期清单。 一旦你有了这些,你应该把它们存储在一张表中,并按照升序列表。 然后做:

 Dim holiday As Boolean For holRow = 1 To N If Month(Date) = Month(Cells(holRow,1).Value) And _ Day(Date) = Day(Cells(holRow,1).Value) Then holiday = True End If Next If Not holiday And Not IsWeekend(Date) And _ Format(Time, "hhmm") > 1710 And Format(Time, "hhmm") < 2015 Then Do Stuff Else Stop End If 

编辑:忘记VBA没有AndAlso

我认为工作日的function适用于你的情况。 您可以将date存储在Excel中的某个范围内,也可以存储在代码中的数组中。 我做了几个假期。

 Sub isTimeToDoThings() Dim time As Date Dim tomorrow As Date Dim nextWorkDay As Date Dim holidays(3) As Date Set wf = Application.WorksheetFunction holidays(0) = CDate("1 / 1 /" & Year(Now())) 'New Years holidays(1) = CDate(ThanksgivingDate(Year(Now()))) 'Thanksgiving time = Date tomorrw = Date + 1 nextWorkDay = CDate(wf.WorkDay(time, 1)) If Format(time, "hhmm") > 1710 And Format(time, "hhmm") < 2015 _ And tomorrow = nextWorkDay Then 'Do stuff Else Stop End If End Sub Public Function ThanksgivingDate(Yr As Integer) As Date ThanksgivingDate = DateSerial(Yr, 11, 29 - _ Weekday(DateSerial(Yr, 11, 1), vbFriday)) End Function