我有一个代码可以在用户表单上设置5分钟的计时器。当我按下命令按钮时,它可以工作。
如何使它在开始时自动运行?我在ThisWorkbook
中尝试过,但没有成功。
这是代码:
在模块中:
Public Const AllowedTime As Double = 1
在用户表单中:
Private Sub CommandButton1_Click()
Dim userClickedPause As Boolean ' Gets set to True by the Pause button
Dim stopTime As Date
userClickedPause = False
' If AllowedTime is the number of minutes with a decimal part:
stopTime = DateAdd("s", Int(AllowedTime * 600), Now) ' add seconds to current time
' If AllowedTime is the number of seconds:
'stopTime = DateAdd("s", AllowedTime, Now) ' add seconds to current time
Do
With UserForm1.TextBox1
.Value = Format(stopTime - Now, "Nn:Ss")
End With
DoEvents
If userClickedPause = True Then
Exit Do
End If
Loop Until Now >= stopTime
End Sub
Private Sub CommandButton2_Click()
userClickedPause = True
End Sub
答案 0 :(得分:1)
我建议您重新组织代码。由于您想同时通过UserForm
和Workbook_Open
事件来调用StartTimer子项,因此请将其放入模块中。
然后,您只需在Commandbutton1_Click
事件和Workbook_Open
事件中调用sub。
'Put this code inside ThisWorkbook
Private Sub Workbook_Open()
'This sub into ThisWorkbook
Application.Run "SetTimer"
End Sub
'This sub goes into a module
Private Sub SetTimer()
'Here goes your code that sets the timer
'(move it from your UserForm)
'.......................................
'.......................................
End Sub
'The code inside your UserForm
Private Sub CommandButton1_Click()
Application.Run "SetTimer"
End Sub