如果時間在下午5點10分至8點15分之間,我有一個運行函數的if條件。在if函數中添加工作日
如何添加另一個條件,說只有在工作日和時間在下午5點10分到8點15分之間時才運行該函數。
下面請看代碼:
If Format(Time, "hhmm") > 1710 And Format(Time, "hhmm") < 2015 Then
Do stuff
Else
Stop
End If
我想避開週末及節假日期間運行的代碼。
千恩萬謝
如果時間在下午5點10分至8點15分之間,我有一個運行函數的if條件。在if函數中添加工作日
如何添加另一個條件,說只有在工作日和時間在下午5點10分到8點15分之間時才運行該函數。
下面請看代碼:
If Format(Time, "hhmm") > 1710 And Format(Time, "hhmm") < 2015 Then
Do stuff
Else
Stop
End If
我想避開週末及節假日期間運行的代碼。
千恩萬謝
使用在@ Zaider的鏈接IsWeekend功能。就像@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
解決你方倍,看起來與TimeSerial function時間值實際時間值,而不是字符串。使用Weekday function確定週一至週五的數值。
If Time >= TimeSerial(17, 10, 0) And Time <= TimeSerial(20, 15, 0) And Weekday(Date, 2) <6 Then
Do stuff
Else
Stop
End If
請注意,我正在使用[平日功能](https://msdn.microsoft.com/en-us/library/82yfs2zh.aspx)以及可選的** FirstDayOfWeek **作爲** ** FirstDayOfWeek.Monday。這意味着星期一是** 1 **,星期六** ** **因此'和平日(日期2)<6'。 – Jeeped
我認爲workday函數適用於您的情況。您可以將日期存儲在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
看到這個問題:檢查是否週末(http://stackoverflow.com/questions/1580432/how-to-determine-if-a-date-falls-on-the-weekend) – Zaider
你將需要生成銀行假期列表。 –
請標記此問題的正確答案 –