每15分钟正确运行一次Macro问题

时间:2015-07-13 16:45:13

标签: excel vba excel-vba

我有这个代码(见下文),假设每15分钟运行一次代码,以便从yahoo finance刷新我的数据并记录在适当的单元格中。一旦我第一次运行它,宏就会自行运行。它会在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

enter image description here

1 个答案:

答案 0 :(得分:1)

全局变量意味着宏可以访问任何例程或函数。通过在代码的其余部分之外(上方)执行它来声明变量global。

Chip有一个很好的教程可以解决您的问题。

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

public class MyDependency<T> : IMyDependency<T>
{
    private string objectName = typeof(T).Name;

    public void WhatGenericTypeIAm()
    {
        Console.WriteLine("My generic type is " + objectName);
    }
}

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

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

这将在当前时间后两分钟存储在变量RunWhen中运行过程的时间。

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

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

此过程执行您在其中包含的任何代码,然后在最后调用StartTimer过程来安排另一个OnTime事件。这就是定期调用的实现方式。请注意,如果在OnTime事件挂起时关闭工作簿,Excel将重新打开该工作簿以执行该过程,并且在OnTime事件完成后不会关闭工作簿。