申请准时

我正在面对vba中的OnTime方法的几个问题。 代码应该每隔30分钟运行一次,但不知何故,它会在两次之间运行几次。 我假设这是因为几个OnTime方法可能正在运行时,我重置并重新运行的代码。 所以我想杀了时间的function,但得到错误。 这里是我的代码如下:

初始代码:

 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 

感谢大家……经过R3uk和eirikdaude的build议,下面的代码完美地工作:

 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 

你正在宣布timetorun 2次

  1. 一个作为一个公共variables和
  2. 一个作为autorefresh的局部variables填充它,所以你会在killontime有一个空的killontime ,这就是为什么你有错误

更多细节在这里: CPearson在OnTime方法

所以你的代码应该是这样的:

 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