VBA:我如何真正停止Application.onTime()?

时间:2013-11-15 13:53:34

标签: excel vba excel-vba timer ontime

[已解决]:请参阅解决方案的答案。谢谢@DaveU。

我已经阅读了一些有关如何停止VBA Application.OnTime过程的问题/主题(例如thisthis),但我无法让它停止!< / p>

我每隔x秒使用它来提取一些数据。我理解当我调用OnTime()方法时,我需要将用于调度事件的相同时间值传递给它。

我还试图引入多个命令(例如试图导致错误)停止执行但它仍然无效!该程序一直在运行......这就是我的代码的样子:

在工作表代码中我有:

Public TimerActive As Boolean
Public tick As String
Public idx As Long
Public counter As Long

Public Sub UpdateOff_Click()

    TimerActive = False
    tick = "Off"
    counter = 1
    idx = 1

    Call StopTimer(idx, counter, tick, TimerActive)
    End ' force quit??

End Sub

Public Sub UpdateOn_Click()

    TimerActive = True
    tick = "live"
    counter = 1
    idx = 1

    Call StartTimer(idx, counter, tick, TimerActive)

End Sub

在一个单独的模块中我有:

Public fireTime As Date

Sub StartTimer(ByVal idx As Long, ByVal counter As Long, ByVal tick As String, ByVal TimerActive As Boolean)

    fireTime = Now + TimeValue("00:00:05")
    sMacro = "  'pullData " & idx & " , " & counter & ", " & Chr(34) & tick & Chr(34) & ", " & TimerActive & "'"
    Application.OnTime EarliestTime:=fireTime, Procedure:=sMacro, Schedule:=True

End Sub

Sub StopTimer(ByVal idx As Long, ByVal counter As Long, ByVal tick As String, ByVal TimerActive As Boolean)

    sMacro = "cause error" ' cause an error (by giving false sub name so program stops?

    Application.OnTime EarliestTime:=fireTime, Procedure:=sMacro, Schedule:=False
    End

End Sub


Public Sub pullData(ByVal idx As Long, ByVal counter As Long, ByVal tick As String, ByVal TimerActive As Boolean)
DoEvents
If TimerActive = True Then

    ' pull the data do some stuff, print the data, etc...

    idx = idx + 1
    counter = counter + 1
    tick = tick + " ."
    If counter = 6 Then
        counter = 1
        tick = "live"
    End If

    Call startTimer(idx, counter, tick, TimerActive)

End If

End Sub

据我所知,我可能已经采取了一些额外的措施来阻止执行,但似乎都没有效果!

1 个答案:

答案 0 :(得分:5)

这是因为你的开始和;停止例程指的是不同的宏。将宏定义为公共,然后它将工作

Public sMacro As String
Public fireTime As Date

Sub startTimer(ByVal idx As Long, ByVal counter As Long, ByVal tick As String, ByVal TimerActive As Boolean)
    fireTime = Now + TimeValue("00:00:05")
    sMacro = "  'pullData " & idx & " , " & counter & ", " & Chr(34) & tick & Chr(34) & ", " & TimerActive & "'"
    Application.OnTime EarliestTime:=fireTime, Procedure:=sMacro, Schedule:=True
End Sub

Sub StopTimer(ByVal idx As Long, ByVal counter As Long, ByVal tick As String, ByVal TimerActive As Boolean)
    Application.OnTime EarliestTime:=fireTime, Procedure:=sMacro, Schedule:=False
End Sub