vba - Excel VBA 中用户表单上的计时器

标签 vba excel userform

我有一些旧的 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/

相关文章:

vba - 如何根据文本框值过滤列表框值

vba - 如何从范围变量中获取表的名称?

vba - PDF 到 Excel 转换将每个 pdf 页面放在不同的工作表中

excel - VBA 通过单击按钮创建一个新工作簿

excel - 如何使用 VBA 从 Excel 向服务器发送 HTTP POST 请求?

vba - 使用 VBA 将选项卡添加到 Excel 中的多页用户窗体

excel - VBA-运行时错误9并使用*作为变量工作表名称

excel - 如何使用按钮隐藏/取消隐藏列?

excel - 在 Excel 中求平均值时将 -ve 数字转换为零

excel - VB在多页中右键单击复制/粘贴