我有一个application.ontime例程,如下所示。
Sub timer()
If Hour(Time) <= 15 Or Hour(Time) >= 22 Then
On Error Resume Next
Application.OnTime EarliestTime:=ThisWorkbook.Worksheets("Sheet1").Range("K5"), Procedure:="dataextract", Schedule:=False
On Error GoTo 0
ThisWorkbook.Worksheets("Sheet1").Range("K5") = Now + TimeSerial(0, WorksheetFunction.Floor(Minute(Now), 5) + 5 - Minute(Now), 1 - Second(Now))
Application.OnTime EarliestTime:=ThisWorkbook.Worksheets("Sheet1").Range("K5"), Procedure:="dataextract", Schedule:=True
End If
End Sub
我希望此例程在day 0
的晚上10点到day 1
的下午4点之间运行,然后在day 1
的晚上10点到day 2
的下午4点自行重启,并且等等。代码在下午4点停止,但不会在晚上10点重新启动。正如你所看到的,我永远不会转向schedule:=false
所以我不明白它为什么不重启..?
答案 0 :(得分:1)
我确定我在某处犯了一个错误,但你应该明白这个想法......
Sub timer()
Const PROC As String = "dataextract"
Const INTV_MIN As Long = 5
Dim rTime As Range
Set rTime = ThisWorkbook.Worksheets("Sheet1").Range("K5")
On Error Resume Next
Application.OnTime EarliestTime:=rTime.Value, Procedure:=PROC, Schedule:=False
On Error GoTo 0
If Hour(Time) <= 15 Or Hour(Time) >= 22 Then
'5min from now
rTime.Value = Now + TimeSerial(0, _
WorksheetFunction.Floor(Minute(Now), INTV_MIN) + INTV_MIN - Minute(Now), _
1 - Second(Now))
Else
'10pm today
rTime.Value = Date + TimeSerial(22, 0, 0)
End If
Application.OnTime EarliestTime:=rTime.Value, Procedure:=PROC, Schedule:=True
End Sub