vba VBA如何在用户窗体中显示实时时钟?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/13449743/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
VBA how to display real time clock in a userform?
提问by thaweatherman
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!
但是我不确定把这段代码放在哪里。任何建议将不胜感激!
采纳答案by thaweatherman
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.
我解决了其他人在所选答案中使用给定代码遇到的问题。我删除了 latesttime 行,并将 Label1.caption = Now() 改为使用 Time() 。
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.
然后我在我的 userform_initialize 函数中调用了它。Label1.caption 已更改为我的用户表单上的相应标签。
Thanks for all of the help!!
谢谢大家的帮助!!
回答by Tomalak
Excel has the OnTime
methodthat allows you to schedule the execution of any procedure.
Excel有该OnTime
方法,可以让你安排任何程序的执行。
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.
通过调用DisplayCurrentTime()
一次来启动循环,例如在表单的 initialize 方法中。
回答by Jook
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.
您的 Excel 会占用相当多的 CPU 时间,甚至可能会阻止用户输入,因为它会尽可能快地执行您的 while 语句。
Look at this example http://www.andypope.info/vba/clock.htmor at the solutions in this post How do I show a running clock in Excel?
看看这个例子http://www.andypope.info/vba/clock.htm或这篇文章中的解决方案如何在 Excel 中显示正在运行的时钟?
They should help you.
他们应该帮助你。
At least you should include a DoEvents
statement in your loop.
至少你应该DoEvents
在循环中包含一个语句。