2

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

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'。此工作簿中可能不可用该宏,或者可能禁用所有宏。

我已经通过“信任中心->信任中心设置->宏设置->启用所有宏,它没有工作。

还单击了“信任对 VBA 项目对象模型的访问”框。

4

2 回答 2

6

首先,这是您尝试从工作表(而不是模块)运行 OnTime 时遇到的错误的快照,正如我将解释的那样。我也遇到了这个错误并试图找出原因。 无法运行宏

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

要在计时器上运行代码,您必须将其添加到VBA 模块。转到 VisualBasic 编辑器并右键单击 VBAProject(书)。在 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 子例程中添加您希望它每次执行的代码。

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

另外,我发现它很片状。如果你在 OnTime 调用中有任何轻微的错误,它都会默默地失败。复制我的代码(我测试过)并先尝试。运行后,只需将您的代码添加到 RefreshAction 子程序。

开始进程()

运行 StartProcess 以开始工作。

另外奇怪的事情

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

于 2017-03-13T21:45:24.187 回答
1

有关更多详细信息,请参阅绝对参考: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
于 2015-11-17T07:22:12.210 回答