不能 运行 宏

Cannot run the macro

我在下面的宏中遇到了问题

Sub RefreshAction()
    Range("b7").Select
    Application.Run "RefreshCurrentSelection"
    Application.OnTime (Now() + TimeValue("00:00:05")), "thisworkbook.Action"
End Sub

当我第一次 运行 宏时单元格刷新,但我在

之后立即收到错误消息

消息:无法 运行 宏“C\Desktop\XYZ.xlsm'!thisworkbook.Action”。该工作簿中可能没有该宏,或者所有宏都已禁用。

我已经完成了“信任中心->信任中心设置->宏设置->启用所有宏,但没有用。

"Trust access to VBA project object model"框也被点击了。

更多细节参见绝对参考:CPearson OnTime

第一期,您需要存储在OnTime 方法中输入的时间才能停止它。 (这里我声明了一个Public TimeToRun As Date

第二点 要连续使用OnTime方法,您需要在计时过程结束时重置计时器(此处为RefreshAllStaticData)。

因此您的整个代码应如下所示:

Public TimeToRun As Date 'so that TimeToRun can be used in both the functions

Sub RefreshAction()
    Range("b7").Select
    Application.Run "RefreshCurrentSelection"
    DoEvents
    'Store the next date of execution in TimeToRun
    TimeToRun = Now() + TimeValue("00:00:05")
    'Launch the next OnTime
    Application.OnTime TimeToRun, "RefreshAllStaticData"
End Sub


Sub RefreshAllStaticData()

'--++-- Place your code here, as it is now --++--

'----Call RefreshAction to reset the OnTime method
'---------to another 5 seconds and keep "looping"
RefreshAction

End Sub


Sub Kill_OnTime()
'Launch this to stop the OnTime method
Application.OnTime _
    earliesttime:=TimeToRun, _
    procedure:="RefreshAllStaticData", _
    schedule:=False
End Sub

首先,这是您尝试从工作表(而非模块)运行 OnTime 时遇到的错误的快照,我将对此进行解释。我也遇到了这个错误,并试图找出原因。

它看起来像一个安全错误,但在这种情况下它不完全是一个正常的安全错误。

要运行 计时器代码,您必须将其添加到VBA 模块。 转到 VisualBasic 编辑器并右键单击 VBAProject (book)。 在 Excel 中,它看起来像下面这样:

添加模块后,您可以在其中添加计时器代码。

由于您想每 5 秒调用一次 RefreshAction,您可以执行如下操作:

Sub StartProcess()
    Debug.Print Now()
    Application.OnTime Now() + TimeValue("00:00:05"), "RefreshAction", Schedule = True
End Sub

Sub RefreshAction()
    Application.EnableEvents = True
    Debug.Print Now() + TimeValue("00:00:05")
    Application.OnTime Now() + TimeValue("00:00:05"), "RefreshAction", Schedule = True
End Sub

我会让您在 RefreshAction 子例程中添加您希望它每次执行的代码。

这是它在模块中的样子。确保你的显示它在一个模块中,就像它在图像中一样:

此外,我发现它非常不稳定。如果您在 OnTime 调用中有任何错误,即使是轻微的错误,它也会默默地失败。复制我的代码(我测试过)并先尝试一下。一旦它 运行s,只需将您的代码添加到 RefreshAction 子。

StartProcess()

运行 StartProcess 开始运行。

另外一件奇怪的事

添加该模块后,我的代码仍然在工作表中,我返回并尝试 运行 它以再次查看错误,奇怪的是一旦代码在模块中您不会再从工作表中得到错误。它现在可能正在引用模块中的代码。