VBA how to display real time clock in a userform?

后端 未结 3 542
青春惊慌失措
青春惊慌失措 2021-01-14 12:03

So I need to display a real-time clock on my form but I am not sure how. I do know that the code:

TimeValue(Now)

will give me the current t

相关标签:
3条回答
  • 2021-01-14 12:31

    I solved the issue others were having with the given code in the chosen answer. I removed the latesttime line and i changed Label1.caption = Now() to use Time() instead.

    Sub DisplayCurrentTime()
        Dim nextSecond As Date
    
        nextSecond = DateAdd("s", 1, Now())
    
        Label1.Caption = Time()
    
        Application.OnTime _
            Procedure:="DisplayCurrentTime", _
            EarliestTime:=nextSecond
    End Sub
    

    I then called this in my userform_initialize function. Label1.caption was changed to the appropriate label on my userform.

    0 讨论(0)
  • 2021-01-14 12:34

    Excel has the OnTime method that allows you to schedule the execution of any procedure.

    Just use it to schedule a one-second rhythm.

    Sub DisplayCurrentTime()
      Dim nextSecond As Date
    
      nextSecond = DateAdd("s", 1, Now())
    
      Label1.Caption = Now()
    
      Application.OnTime _
        Procedure:="DisplayCurrentTime", _
        EarliestTime:=nextSecond, _
        LatestTime:=nextSecond
    End Sub
    

    Start the loop by calling DisplayCurrentTime() once, for example in the initialize method of your form.

    0 讨论(0)
  • 2021-01-14 12:34

    The problem with your atempt would be, that you are effectively creating an infinite loop.

    Your Excel would use up quite some CPU-Time and might even block user-input, because it would excecute your while-statements, as fast as it can.

    Look at this example http://www.andypope.info/vba/clock.htm or at the solutions in this post How do I show a running clock in Excel?

    They should help you.

    At least you should include a DoEvents statement in your loop.

    0 讨论(0)
提交回复
热议问题