vba - OnTime 函数困惑

标签 vba excel

我写下了下面的VBA代码,每5秒执行一次,但它不起作用。

Option Explicit

Public RunWhen As Double
Public Const cRunIntervalSeconds = 5 ' two minutes
Public Const cRunWhat = "TheSub"  ' the name of the procedure to run

Sub StartTimer()
    RunWhen = Now + TimeValue(0, 0, cRunIntervalSeconds)
    Application.OnTime EarliestTime:=RunWhen, Procedure:=cRunWhat, _
        Schedule:=True
End Sub


Sub TheSub()
    ''''''''''''''''''''''''
    ' Your code here
    ''''''''''''''''''''''''
    MsgBox "hi this is working"
    StartTimer  ' Reschedule the procedure
End Sub

我在这里缺少什么?

像下面这样的简单表达式也不起作用

Sub test()
    Application.ontime (now() + TimeValue("0:0:5")),"test"
End Sub

最佳答案

您应该使用TimeSerial函数,而不是TimeValue .

Option Explicit

Public RunWhen As Double
Public Const cRunIntervalSeconds = 5 ' two minutes
Public Const cRunWhat = "TheSub"  ' the name of the procedure to run

Sub StartTimer()
    RunWhen = Now + TimeSerial(0, 0, cRunIntervalSeconds)
    Application.OnTime EarliestTime:=RunWhen, Procedure:=cRunWhat
End Sub


Sub TheSub()
    ''''''''''''''''''''''''
    ' Your code here
    ''''''''''''''''''''''''
    Debug.Print "hi this is working"
    StartTimer  ' Reschedule the procedure
End Sub

这有效,您可以观看 VBE 的立即窗口来查看它的运行情况。

关于vba - OnTime 函数困惑,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38989522/

相关文章:

excel - 如何使用 XML 解析更可靠地删除 Excel 单元格中的删除线文本?

excel - 打开目录中的所有 MSProject 文件 - Excel VBA

vba - 在使用的单元格范围VBA中应用边框

excel - 下标超出范围错误(Error 9) : . FormatConditions

vba - 使用 VBA 在 Skype 中发送消息

string - 在 Windows 资源管理器中搜索文件的 VBA 字符串

excel - 使用复制目标和选择性粘贴来保持格式

excel - 使用IF语句检查值

python - 使用 pandas 创建平均数据框

vba - 如何使用间接引用在vba中选择单个单元格或范围