VBA如何在用户窗体中显示实时时钟?

tha*_*man 3 excel vba excel-vba

所以我需要在表单上显示一个实时时钟,但我不知道如何.我知道代码:

TimeValue(Now)
Run Code Online (Sandbox Code Playgroud)

会给我当前的时间,但我不知道如何在我的表格上不断显示.

我有一个想法是将此代码放在循环中,如下所示:

Dim bool As Boolean
bool = True
Do While bool = True
    Label1.Caption = TimeValue(Now)
Loop
Run Code Online (Sandbox Code Playgroud)

但是我不知道在哪里放这个代码.任何建议将不胜感激!

Tom*_*lak 6

Excel有OnTime方法,可以让你安排任何程序的执行.

只需用它来安排一秒钟的节奏.

Sub DisplayCurrentTime()
  Dim nextSecond As Date

  nextSecond = DateAdd("s", 1, Now())

  Label1.Caption = Now()

  Application.OnTime _
    Procedure:="DisplayCurrentTime", _
    EarliestTime:=nextSecond, _
    LatestTime:=nextSecond
End Sub
Run Code Online (Sandbox Code Playgroud)

通过调用DisplayCurrentTime()一次启动循环,例如在表单的initialize方法中.