Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

VBA how to display real time clock in a userform?

Tags:

excel

vba

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 time, but I am not sure how to continually display this on my form.

I have an idea which is to put this code inside of a loop as follows:

Dim bool As Boolean
bool = True
Do While bool = True
    Label1.Caption = TimeValue(Now)
Loop

However I am not sure where to put this code. Any suggestions would be greatly appreciated!

like image 709
thaweatherman Avatar asked Sep 17 '25 20:09

thaweatherman


2 Answers

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.

like image 122
Tomalak Avatar answered Sep 19 '25 10:09

Tomalak


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.

like image 39
Jook Avatar answered Sep 19 '25 10:09

Jook