如何在Excel中显示运行时钟?
我想在Excel 2007的单元格A1中显示一个时钟。我熟悉NOW()和TODAY(),但它并不像我想要的那样每1分钟刷新一次。 你知道,就像一个跑步的时钟。 我只希望h:mm的当前时间位于单元格A1中。 这可能吗?
从这个时钟开始,我会进行进一步的计算,比如自从我上次做了多久以来,活动X,Y和Z.谢谢。
看下面的代码( 取自这个职位 )
把这段代码放入VBA中的模块(开发人员标签 – > Visual Basic)
Dim TimerActive As Boolean Sub StartTimer() Start_Timer End Sub Private Sub Start_Timer() TimerActive = True Application.OnTime Now() + TimeValue("00:01:00"), "Timer" End Sub Private Sub Stop_Timer() TimerActive = False End Sub Private Sub Timer() If TimerActive Then ActiveSheet.Cells(1, 1).Value = Time Application.OnTime Now() + TimeValue("00:01:00"), "Timer" End If End Sub
您可以在工作簿打开时调用“StartTimer”函数,并通过将以下代码添加到Visual Basic编辑器中的工作簿Visual Basic“This.Workbook”类中,使其每分钟重复一次。
Private Sub Workbook_Open() Module1.StartTimer End Sub
现在,每过1分钟,将调用Timer过程,并将单元格A1设置为当前时间。
find我在上面评论中提到的代码 。 要testing它,请执行以下操作:
- 在
Sheet1
更改A1
的单元格高度和宽度,如下面的快照所示。 - 通过右键单击格式来显示时间格式
- 在工作表上添加两个button(表格控件),并按照快照中的说明命名
- 将此代码粘贴到模块中
- 右键单击工作表上的“
Start Timer
button,然后单击“Assign Macros
。 selectStartTimer
macros。 - 右键单击工作表上的
End Timer
button,然后单击Assign Macros
。 selectEndTimer
macros。
现在点击开始计时器button,你会看到在单元格A1
更新的时间。 要停止时间更新,请单击结束计时器button。
代码( TRIED AND TESTED )
Public Declare Function SetTimer Lib "user32" ( _ ByVal HWnd As Long, ByVal nIDEvent As Long, _ ByVal uElapse As Long, ByVal lpTimerFunc As Long) As Long Public Declare Function KillTimer Lib "user32" ( _ ByVal HWnd As Long, ByVal nIDEvent As Long) As Long Public TimerID As Long, TimerSeconds As Single, tim As Boolean Dim Counter As Long '~~> Start Timer Sub StartTimer() '~~ Set the timer for 1 second TimerSeconds = 1 TimerID = SetTimer(0&, 0&, TimerSeconds * 1000&, AddressOf TimerProc) End Sub '~~> End Timer Sub EndTimer() On Error Resume Next KillTimer 0&, TimerID End Sub Sub TimerProc(ByVal HWnd As Long, ByVal uMsg As Long, _ ByVal nIDEvent As Long, ByVal dwTimer As Long) '~~> Update value in Sheet 1 Sheet1.Range("A1").Value = Time End Sub
快照