excel - 使用 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
解决方案
当您取消计时器时,您必须使用与设置它时相同的确切时间,因此:
-----用户表单-----
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
推荐阅读
- python - AttributeError: 'English' 对象没有属性 'vocal'
- sql - 连接一个表包含整理列的表
- python - 在 Python 中解析 .pdb 文件并为特定记录类型创建字典
- pandas - 将 Str 转换为从 Beautifulsoup 中提取的日期时间
- android - 如何仅为一个回收器视图适配器设置不同的 OnClickListener
- javascript - 如何在Javascript中使用子菜单防止响应式下拉子菜单li中的默认行为
- java - 在远程机器上启动 ActiveMQ BrokerService
- dataset - 即使输入正确,估计器也不起作用
- sas - 在 SAS 中使用 PROC SQL 进行日期比较
- excel - 迭代命名范围以与 LINEST 一起使用