当更换其他单元时,Vba秒表无意中重置0

我在Excel电子表格中有一个VBA秒表,代码:

Public StopIt As Boolean Public ResetIt As Boolean Public LastTime Private Sub CommandButton1_Click() Dim StartTime, FinishTime, TotalTime, PauseTime StopIt = False ResetIt = False If Range("C2") = 0 Then StartTime = Timer PauseTime = 0 LastTime = 0 Else StartTime = 0 PauseTime = Timer End If StartIt: DoEvents If StopIt = True Then LastTime = TotalTime Exit Sub Else FinishTime = Timer TotalTime = FinishTime - StartTime + LastTime - PauseTime TTime = TotalTime * 100 HM = TTime Mod 100 TTime = TTime \ 100 hh = TTime \ 3600 TTime = TTime Mod 3600 MM = TTime \ 60 SS = TTime Mod 60 Range("C2").Value = Format(hh, "00") & ":" & Format(MM, "00") & ":" & Format(SS, "00") & "." & Format(HM, "00") If ResetIt = True Then Range("C2") = Format(0, "00") & ":" & Format(0, "00") & ":" & Format(0, "00") & "." & Format(0, "00") LastTime = 0 PauseTime = 0 End End If GoTo StartIt End If End Sub Private Sub CommandButton2_MouseDown(ByVal Button As Integer, ByVal Shift As Integer, ByVal X As Single, ByVal Y As Single) StopIt = True End Sub Private Sub CommandButton3_Click() Range("C2").Value = Format(0, "00") & ":" & Format(0, "00") & ":" & Format(0, "00") & "." & Format(0, "00") LastTime = 0 ResetIt = True End Sub 

这个秒表正常工作。 我的问题是,当我更改电子表格中的单元格或进行任何更改时,将秒表重置为“0”。

我希望它在整个会话中运行,因为我有其他单元格引用此计数器。

任何帮助将不胜感激。 寻找解决scheme时,我找不到任何类似的问题。

谢谢

不知道你是否find了解决scheme,但我做了一些研究,并认为我知道为什么你的代码不工作,并可能有另一种解决scheme…如果可以接受…

当我通过启动计时器来testing代码,然后更改任何单元格时,它不会重置为零,但会停止计时器。 看看你的代码(这可能来自https://www.extendoffice.com/documents/excel/3684-excel-create-stopwatch.html ),代码仅适用于使用简单的计时器…没有其他。 而且由于它在你停止之前永远不会放弃控制,所以它使用了大量的处理器(看看任务pipe理器!)

我确实在Stack VBA Macro On Timer样式中find了代码,每运行一组秒数,即120秒,并使用第二个答案(简单地懒得在启动时使用第一个答案) 运行代码 。

您现在可以更改单元格,并且代码继续运行(除了在对单元格进行更改时“暂停”)。 你可能不喜欢这个数字增加的事实,但也许别人知道这个解决scheme。

代码不会进入工作表模块。

 Option Explicit Dim TimerActive As Boolean Sub StartTimer() Start_Timer End Sub Private Sub Start_Timer() TimerActive = True Application.OnTime Now() + TimeValue("00:00:01"), "Timer" End Sub Private Sub Stop_Timer() TimerActive = False End Sub Private Sub Timer() If TimerActive Then Activesheet.Cells(2, 3).value = Time Application.OnTime Now() + TimeValue("00:00:01"), "Timer" End If End Sub 
    Interesting Posts