我在vba中遇到了OnTime
- 方法的问题。该代码应该每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
我修改了下面的代码,以便在需要时重置ontime。
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 :(得分: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 :(得分:-2)
您宣布timetorun
2次:
autorefresh
中的填充的局部变量,因此timetorun
中的killontime
为空{这就是你'的原因得到了错误此处有更多详细信息: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