2016-08-17 124 views
2

我已經寫下VBA代碼下面每5秒執行一次,但它不起作用。OnTime函數混淆

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 
+0

如果您打算在完成調用過程後重新運行StartTimer,則不要安排OnTime。 – Jeeped

+0

@Jeeped我需要安排OnTime以保持這些函數循環調用。 –

+1

'RunWhen = Now + TimeSerial(0,0,cRunIntervalSeconds)'Not「TimeValue」 –

回答

2

你應該使用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的即時窗口,看看它貫穿。

+0

哦,好吧,我的壞,我只是混合這兩個功能,並迷惑自己 –