首页 文章

无法运行宏

提问于
浏览
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项目对象模型”框 .

2 回答

  • 1

    有关详细信息,请参阅绝对参考:CPearson OnTime

    First issue ,您需要存储您在 OnTime 方法中输入的时间才能停止它 . (这里我宣布公共TimeToRun为日期)

    Second Point 要连续使用 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
    
  • 4

    首先,我将解释当您尝试从工作表(而不是模块)运行OnTime时获得的错误的快照 . 我也得到了这个错误并试图找出原因 .
    cannot run macro

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

    要在计时器上运行代码,您必须将其添加到 VBA module . 转到VisualBasic编辑器并右键单击VBAProject(书) . 在Excel中,它看起来如下所示:

    add module
    添加模块后,在那里添加定时器代码 .

    由于您希望每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子例程中添加您希望它每次执行的代码 .

    这是模块中的样子 . 确保你的图像在图像中显示它在模块中:
    module in vba

    而且,我发现它非常脆弱 . 如果您在OnTime调用中有任何轻微错误,它将无声地失败 . 复制我的代码(我测试过它)并先尝试一下 . 运行后,只需将代码添加到RefreshAction子 .

    StartProcess()

    运行StartProcess开始运行 .

    Additionally Odd Thing

    在我添加该模块之后,我仍然在工作表中使用了我的代码,然后我回去尝试运行它以再次看到错误,奇怪的是,一旦代码在模块中,您将无法从错误中获取错误工作表了 . 它现在可能正在引用模块中的代码 .

相关问题