为什么我的application.ontime不能在if语句中工作? VBA

时间:2016-11-04 03:30:56

标签: excel vba excel-vba

我有一个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所以我不明白它为什么不重启..?

1 个答案:

答案 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