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!
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With