2015-11-17 163 views
2

我面臨幾個問題與我的OnTime -method vba。代碼應該每30分鐘運行一次,但不知何故它會在兩次之間運行幾次。我假設這是因爲當我重置並重新運行代碼時,幾個OnTime-方法可能正在運行。所以我想殺了準時的功能,但得到錯誤。這裏是我下面的代碼:申請準時

初始代碼:

Sub autorefresh() 
    dim timetorun 

    timetorun = Now + TimeSerial(0, 30, 0) 

    Application.OnTime timetorun, "manager" 'this runs the macro manager which 
              'runs several other macros and in 
              'the end calls this macro again in 
              'order to reset the timetorun counter 
End Sub 

我修改了下面的代碼,如果需要重置準時。

Public timetorun As Date 'so that timetorun can be used in both the functions 

Sub autorefresh() 

    timetorun = Now + TimeSerial(0, 30, 0) 
    Application.OnTime timetorun, "manager" 

End Sub 

Sub killontime() 

    Application.OnTime earliesttime:=timetorun, procedure:="manager", schedule:=False '<~~this line gives the error 

End Sub 
+0

如果公共'timetorun'已被'其他'功能改變,那麼它不能被用來取消第一個預定的宏。 – Jeeped

+0

@Jeeped:它可能,但第一個問題是它在不同的範圍內被宣佈2次! ;) – R3uK

+0

@ R3uK - 嗯...我已經推斷,它公開後,它被從子刪除,但你可以很好地解決這個問題;即如果它也在子中聲明,那麼一個是用來設置時間的,而不是公共的。 – Jeeped

回答

2

謝謝大家......在從R3uk和eirikdaude建議,下面的代碼工作完美:

Public timetorun As Double 

Sub autorefresh() 

    timetorun = Now + TimeSerial(0, 30, 0) 

    Application.OnTime timetorun, "manager" 

End Sub 


Sub killontime() 

    Application.OnTime timetorun, "manager", , False 

End Sub 
-1

您聲明timetorun 2倍

  1. 一個作爲公共變量和
  2. 一個在autorefresh一個局部變量,你填寫它,所以你必須killontime中有一個空的timetorun,這就是爲什麼你有錯誤

在這裏更多細節:CPearson on OnTime method

所以,你的代碼應該是這樣的:

Public TimeToRun As Date 'so that timetorun can be used in both the functions 

Sub autorefresh() 

TimeToRun = Now + TimeSerial(0, 30, 0) 
'this runs the macro manager which runs several other macros and _ 
'in the end calls this macro again in order to reset the timetorun counter... 

Application.OnTime TimeToRun, "manager" 

End Sub 

'I added the below code to reset the ontime if needed. 
Sub killontime() 

Application.OnTime _ 
    earliesttime:=TimeToRun, _ 
    procedure:="manager", _ 
    schedule:=False 

End Sub 

Sub Manager() 

'your code as it is now 

'Call autorefresh to reset the OnTime method to another 30 seconds 
autorefresh 

End Sub 
+0

thnx ...我實際上已經剝皮一次..我想我分享信息的方式令人困惑。現在請檢查問題。它與你所建議的代碼基本相同。 –

+0

你錯誤是什麼?在哪一行?同樣的? (爲其他評論,我認爲這是修復,因爲這對我工作正常) – R3uK

+0

我得到運行時錯誤1004:方法'ontime'object_application失敗 –