我想专门在label8中显示活动时间,但是在用户窗体初始化中调用DisplayCurrentTime()
时遇到问题。
我是初次接触vba的人,正在浏览Stackoverflow寻找答案
Private Sub UserForm_Initialize()
Book2.UserForm1.DisplayCurrentTime
End Sub
我有这些可以尝试称呼它
Sub DisplayCurrentTime()
Dim nextSecond As Date
nextSecond = DateAdd("s", 1, Now())
Label8.Caption = Time()
Application.OnTime _
Procedure:="DisplayCurrentTime", _
EarliestTime:=nextSecond, _
LatestTime:=nextSecond
End Sub
并且我有这些行可以在label8中工作
答案 0 :(得分:0)
将DisplayCurrentTime
放在UserForm模块内。然后,您可以按以下方式调用子
Private Sub UserForm_Initialize()
Book2.UserForm1.DisplayCurrentTime
End Sub
Private Sub DisplayCurrentTime()
Dim nextSecond As Date
nextSecond = DateAdd("s", 1, Now())
Label8.Caption = Time()
Application.OnTime _
Procedure:="UserForm1.DisplayCurrentTime", _
EarliestTime:=nextSecond, _
LatestTime:=nextSecond + 1
End Sub
或者,您可以将DisplayCurrentTime
放在另一个模块中。但是,您正在UF中填充控件,因此必须指定UF。以下过程适用于任何UserForm。
Private Sub UserForm_Initialize()
DisplayCurrentTime Me, "Label8"
End Sub
在下面的另一个模块中
Sub DisplayCurrentTime(UF As UserForm, Cntrl_Name As String)
Dim nextSecond As Date
nextSecond = DateAdd("s", 1, Now())
UF.Controls.Item(Cntrl_Name).Caption = Time()
'If the control you want to paste the date to is Label8 for every UF, use the commented out code instead..
'..and remove ", Cntrl_Name As String" from this sub, and...
'..remove the specified control in the UserForm_Initialize sub
'UF.Controls.Item("Label8").Caption = Time()
'Module1 is true in my case, edit to suit your project
Application.OnTime _
Procedure:="Module1.DisplayCurrentTime", _
EarliestTime:=nextSecond, _
LatestTime:=nextSecond + 1
End Sub
答案 1 :(得分:0)
将DisplayCurrentTime()
过程更改为Public
Public Sub DisplayCurrentTime()
'your code here...
End Sub
这会将“模块级别”设置为可从外部访问。
注意,
Public
Property
和Sub/Function
将对所有模块和所有应用程序中的所有外部对象开放,除非Option Private Module
生效
答案 2 :(得分:0)
在此处找到此代码:https://www.youtube.com/watch?v=H5649YiZjZM
Private Sub UserForm_Activate()
Do
DoEvents
Label8.Caption = Time
Loop
End Sub
此代码可以正常工作并满足我的要求。感谢大家@Tim Stacks和@Rawrplus的所有帮助!