首页 > 解决方案 > 使用 MsgBox 时出现运行时错误“1004”方法“OnTime”

问题描述

如果用户想要结束计时器,我有一个可以正常工作的代码,直到我添加了 MsgBox 确认。每次用户启动任务时,用户窗体只显示一个从零开始的计时器。

我尝试替换"myTimer", , False -> "myTimer", , True但计时器只是在后台继续递增。

-----用户表单-----

Private Sub UserForm_Initialize()
    Call myTimer
    StartTime = Timer
End Sub

Private Sub UserForm_QueryClose(Cancel As Integer, _CloseMode As Integer)
    If MsgBox("Are you sure to End Time?", vbYesNo) = vbYes Then
        myTimer_Cancel
    Else
        Cancel = True
    End If
End Sub

- - -模块 - - -

Option Explicit
Public StartTime As Single
Public Sub myTimer()
    Dim elapsedtime As Single
    elapsedtime = Timer - StartTime
    UserForm2.Label2.caption = Format(CDate(elapsedtime / 86400), "hh:nn:ss")
    Application.OnTime Now + timeValue("00:00:01"), "myTimer"
End Sub

Public Sub myTimer_Cancel()
    Application.OnTime Now + timeValue("00:00:01"), "myTimer", , False
End Sub

标签: excelvbatimer

解决方案


当您取消计时器时,您必须使用与设置它时相同的确切时间,因此:

-----用户表单-----

Private Sub UserForm_Initialize()
    Call myTimer
    StartTime = Timer 
End Sub

Private Sub UserForm_QueryClose(Cancel As Integer, _CloseMode As Integer)
    If MsgBox("Are you sure to End Time?", vbYesNo) = vbYes Then
        myTimer_Cancel
    Else
        Cancel = True
    End If
End Sub

- - -模块 - - -

Option Explicit

Public StartTime As Single
Public NextRun ' << store next run time

Public Sub myTimer()
    Dim elapsedtime As Single
    elapsedtime = Timer - StartTime
    UserForm2.Label2.caption = Format(CDate(elapsedtime / 86400), "hh:nn:ss")
    NextRun = Now + timeValue("00:00:01")
    Application.OnTime NextRun, "myTimer"
End Sub

Public Sub myTimer_Cancel()
    Application.OnTime NextRun, "myTimer", , False
End Sub


推荐阅读