我写下了下面每5秒要执行的VBA代码,但它不起作用。

Option Explicit

Public RunWhen As Double
Public Const cRunIntervalSeconds = 5 ' two minutes
Public Const cRunWhat = "TheSub"  ' the name of the procedure to run

Sub StartTimer()
    RunWhen = Now + TimeValue(0, 0, cRunIntervalSeconds)
    Application.OnTime EarliestTime:=RunWhen, Procedure:=cRunWhat, _
        Schedule:=True
End Sub


Sub TheSub()
    ''''''''''''''''''''''''
    ' Your code here
    ''''''''''''''''''''''''
    MsgBox "hi this is working"
    StartTimer  ' Reschedule the procedure
End Sub


我在这里想念什么?

同样像下面这样的简单表达式也不起作用

Sub test()
    Application.ontime (now() + TimeValue("0:0:5")),"test"
End Sub

最佳答案

您应该使用TimeSerial函数,而不是TimeValue

Option Explicit

Public RunWhen As Double
Public Const cRunIntervalSeconds = 5 ' two minutes
Public Const cRunWhat = "TheSub"  ' the name of the procedure to run

Sub StartTimer()
    RunWhen = Now + TimeSerial(0, 0, cRunIntervalSeconds)
    Application.OnTime EarliestTime:=RunWhen, Procedure:=cRunWhat
End Sub


Sub TheSub()
    ''''''''''''''''''''''''
    ' Your code here
    ''''''''''''''''''''''''
    Debug.Print "hi this is working"
    StartTimer  ' Reschedule the procedure
End Sub


这可以正常工作,您可以观看VBE的即时窗口以查看其运行过程。

关于excel - 准时功能困惑,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/38989522/

10-10 19:00