秒表在Excel VBA?

我正在设置一个基本的秒表来跟踪已过的时间。 Button1应该开始在0时钟,Button2停止手表,并logging自计时器启动以来经过了多less分钟和秒钟。 我有工作表上的button,只需要一种方法来计算经过的时间。 什么是最好的方法? 这是我一直在使用的代码

Private Sub CommandButton1_Click() startTime = Timer End Sub Private Sub CommandButton2_Click() Dim finalTime As Single finalTime = Timer - startTime MsgBox Format(finalTime, "0.00") End Sub 

这个代码的问题是它显示了我点击button2之后所经过的时间。 我需要在我的Excel表上运行计时器。

 Public Started As Boolean Dim myTime As Date Sub StartTimer() If Not Started Then myTime = Time Started = True Else If MsgBox("Do you really want to restart?", vbYesNo) = vbYes Then myTime = Time End If End If End Sub Sub StopTimer() If Not Started Then MsgBox "The timer is stopped." Else MsgBox Format(Time - myTime, "hh:mm:ss") Started = False End If End Sub 

YouTube的

链接

如果您需要任何准确性,Excel可能不是这样做的地方。 但是,如果足够接近足够接近,那么这就是我将如何做到这一点。

在标准模块中:

 Public gbStop As Boolean Public gdtStart As Date Sub UpdateTime() Sheet1.Range("rngTimer").Value = Now - gdtStart DoEvents If Not gbStop Then Application.OnTime Now + TimeSerial(0, 0, 1), "UpdateTime" End If End Sub 

在Sheet1的类模块中

 Private Sub CommandButton1_Click() gbStop = False gdtStart = Now Application.OnTime Now + TimeSerial(0, 0, 1), "UpdateTime" End Sub Private Sub CommandButton2_Click() gbStop = True End Sub 

当您单击Button1时,gbStop设置为false,开始时间logging在公共variables中,UpdateTime过程计划在1秒后运行。

一秒钟之后,UpdateTime将运行,名为rngTimer的单元格的值将更改为显示Now和Button1_Click中logging的开始之间的已用时间。 如果gbStop仍然是False,则UpdateTime将自己安排在另一秒中再次运行。

最后,您按下Button2,将公共variablesgbStop设置为True。 下次Updatetime运行时,它不会安排自己再次运行。