我有一些旧的 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
关于vba - Excel VBA 中用户表单上的计时器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1562913/