我有一些旧的Excel VBA代码,我想在其中定期运行任务。如果我使用的是VB6,则应该使用计时器控件。

我找到了Application.OnTime()方法,该方法很好地适用于在Excel工作表中运行的代码,但是我无法使其以用户形式运行。该方法永远不会被调用。

如何使Application.OnTime()以用户形式调用方法,或者还有其他方法来计划代码在VBA中运行?

最佳答案

我找到了解决方法。如果您在模块中编写一个仅以您的用户形式调用方法的方法,则可以使用Application.OnTime()安排模块方法。

有点笨拙,但是除非有人有更好的建议,否则它会起作用。

这是一个例子:

''//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

07-24 09:51
查看更多