Excel 自动运行宏,但不在此工作簿中运行

Excel 自动运行宏,但不在此工作簿中运行,excel,vba,Excel,Vba,我有一个在我的用户表单上设置5分钟计时器的代码。当我按下命令按钮时,它工作 如何使其在启动时自动运行?我尝试了这个工作簿,但没有成功 代码如下: 在模块中: Public Const AllowedTime As Double = 1 在Userform中: Private Sub CommandButton1_Click() Dim userClickedPause As Boolean ' Gets set to True by the Pause button Dim stopTim

我有一个在我的用户表单上设置5分钟计时器的代码。当我按下命令按钮时,它工作

如何使其在启动时自动运行?我尝试了
这个工作簿
,但没有成功

代码如下:

在模块中:

Public Const AllowedTime As Double = 1
在Userform中:

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

我建议您重新构造代码。由于您希望从
UserForm
Workbook\u Open
事件调用StartTimer sub,请将其放入模块中

然后,您只需从
命令按钮1\u单击
事件调用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

计时器事件的代码在哪里?没有@braX我也不需要这个代码的暂停功能。我只想看10分钟过去。这就是为什么它“不工作”的原因。@braX我不知道在这个工作簿中放置什么以及代码的哪一部分来让它自动运行。现在,我必须点击一个命令按钮来运行10分钟到0。我想在打开工作簿后运行它。这就是我不知道怎么做的。我将代码
CommandButton1\u Click()
粘贴到
此工作簿中
但没有发生任何事情。您是否将其放置在正确的事件中?或者你只是随机粘贴,没有具体的名字@Codingnoob检查“事件”是否已启用。您可以在VBE内部的“即时窗口”中键入
?Application.EnableEvents
。如果它返回
FALSE
,您可以键入
Application.EnableEvents=True
来启用事件。如果您的代码在
Workbook\u Open()中的
thiswook
中,并且事件启用,我想到的唯一进一步的事情是安全设置,这些设置在工作簿打开时阻止宏运行。但我想你已经检查过了?你试过了吗?它根本不起作用。您还要求告诉我在何处插入
公共Const AllowedTime As Double=1
。我在另一个模块中复制了它,它仍然只有在我单击命令按钮时才起作用。它不会自动运行。公共声明可以在任何模块中(但不能在UserForm、Sheet或ThisWorkbook中)。不,我没有试过,我向你展示了一般的方法——如果做得好,它会起作用。很高兴听到。不确定是否可以修复。可能与运行重载宏时Excel空白的问题相同。