我有一些旧的Excel VBA代码,我想定期运行任务。如果我使用VB6,我会用一个定时器控件。Excel VBA中的用户表单中的计时器
我找到Application.OnTime()方法,它适用于在Excel工作表中运行的代码,但我无法使其在用户窗体中工作。该方法永远不会被调用。
我该如何让Application.OnTime()以用户形式调用方法,或者是否有其他方法来安排代码在VBA中运行?
我有一些旧的Excel VBA代码,我想定期运行任务。如果我使用VB6,我会用一个定时器控件。Excel VBA中的用户表单中的计时器
我找到Application.OnTime()方法,它适用于在Excel工作表中运行的代码,但我无法使其在用户窗体中工作。该方法永远不会被调用。
我该如何让Application.OnTime()以用户形式调用方法,或者是否有其他方法来安排代码在VBA中运行?
我找到了解决方法。如果您在模块中编写方法,只调用用户表单中的方法,则可以使用Application.OnTime()来调度模块方法。
一种kludge,但它会做,除非有人有更好的建议。
下面是一个例子:
''//Here's the code that goes in the user form
Dim nextTriggerTime As Date
Private Sub UserForm_Initialize()
ScheduleNextTrigger
End Sub
Private Sub UserForm_Terminate()
Application.OnTime nextTriggerTime, "modUserformTimer.OnTimer", Schedule:=False
End Sub
Private Sub ScheduleNextTrigger()
nextTriggerTime = Now + TimeValue("00:00:01")
Application.OnTime nextTriggerTime, "modUserformTimer.OnTimer"
End Sub
Public Sub OnTimer()
''//... Trigger whatever task you want here
''//Then schedule it to run again
ScheduleNextTrigger
End Sub
''// Now the code in the modUserformTimer module
Public Sub OnTimer()
MyUserForm.OnTimer
End Sub
如何将所有的代码为“定时器”模块。
Dim nextTriggerTime As Date
Dim timerActive As Boolean
Public Sub StartTimer()
If timerActive = False Then
timerActive = True
Call ScheduleNextTrigger
End If
End Sub
Public Sub StopTimer()
If timerActive = True Then
timerActive = False
Application.OnTime nextTriggerTime, "Timer.OnTimer", Schedule:=False
End If
End Sub
Private Sub ScheduleNextTrigger()
If timerActive = True Then
nextTriggerTime = Now + TimeValue("00:00:01")
Application.OnTime nextTriggerTime, "Timer.OnTimer"
End If
End Sub
Public Sub OnTimer()
Call MainForm.OnTimer
Call ScheduleNextTrigger
End Sub
现在你可以从MainForm的呼吁:
call Timer.StartTimer
call Timer.StopTimer
为了防止出错,补充:
Private Sub UserForm_Terminate()
Call Timer.StopTimer
End Sub
至极触发:
Public Sub OnTimer()
Debug.Print "Tick"
End Sub
我认为这是唯一的方式唐。 – 2009-10-15 15:03:51
非常好的解决方法。 +1 – Tomalak 2012-11-19 19:47:57