macros正常运行15分钟有问题

我有这个代码(见下文),假设每15分钟运行一次代码,以便我的数据从雅虎财经刷新并logging在适当的单元格中。 一旦我第一次运行它,这个macros就会自动运行。 它会在15分钟后第一次运行,然后每2分钟开始运行一次,然后回到15分钟。 这是不一致的。 代码下面是它正在生产的图片。

Sub TimeStamp() ' ' TimeStamp Macro ' ' Keyboard Shortcut: Ctrl+Shift+A ' ' Following refreshes the data Application.CalculateFullRebuild ' Following Inputs Exchange Date (L1) and Time (N1) into next available cell in column A With ActiveSheet With .Cells(Rows.Count, "A").End(xlUp).Offset(1, 0) .Value = Application.Evaluate("CONCATENATE(L1,N1)") .WrapText = False End With End With ' Following inputs the current price of stock (G3) into next available cell in column D With ActiveSheet .Cells(Rows.Count, "D").End(xlUp).Offset(1, 0) = .Range("G3").Value2 End With ' Following inputs the date of the exchange (L1) into next available cell in column B With ActiveSheet.Cells(Rows.Count, "B").End(xlUp).Offset(1, 0) 'this sets the value of B2 with the value of L1 .Value = ActiveSheet.Range("L1").Value2 .WrapText = False End With ' Following inputs the Time of the exchange (N1) into the next available cell in column C With ActiveSheet.Cells(Rows.Count, "C").End(xlUp).Offset(1, 0) 'this sets the value of B2 with the value of L1 .Value = ActiveSheet.Range("N1").Value2 .WrapText = False End With ' Following runs TimeStamp macro every 15 minutes Application.OnTime Now + TimeValue("00:15:00"), "TimeStamp" End Sub 

在这里输入图像说明

全局variables意味着它可以被macros中的任何例程或函数访问。 通过在代码的其余部分之外(上方)声明variablesglobal。

芯片有一个很好的教程,应该解决您的问题。

在任何过程(Sub或Function)声明之外和之前,在标准代码模块中声明公共variables:

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

要启动一个可重复的计时器,请创build一个名为StartTimer的过程,如下所示:

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

这会在当前时间后两分钟存储variablesRunWhen中运行该过程的时间。

接下来,您需要编写将由OnTime调用的过程。 例如,

 Sub TheSub() '''''''''''''''''''''''' ' Your code here '''''''''''''''''''''''' StartTimer ' Reschedule the procedure End Sub 

此过程执行您包含在其中的任何代码,然后调用StartTimer过程调度另一个OnTime事件。 这就是周期性呼叫的实施方式。 请注意,如果在OnTime事件处于挂起状态时closures工作簿,则Excel将重新打开该工作簿以执行该过程,并且在OnTime事件完成后不会closures该工作簿。