每5秒运行一次宏/ VBA

时间:2016-01-11 06:44:49

标签: excel vba

在excel工作表上,我使用Microsoft Power Query创建了几个SQL查询, 这些查询应每5秒刷新一次,以便从SQ数据库中检索新信息。

要刷新,我转到Excel中的数据选项卡,然后点击刷新所有工作簿的全部刷新按钮。这很好用

我想每5秒自动执行一次此请求 理想情况下,A宏应该在后台每5秒运行一次Ctrl + Alt + F5命令。

我怎样才能实现这个目标

2 个答案:

答案 0 :(得分:2)

只需在宏的末尾添加Application.OnTime method即可在5秒内重新运行。

Option Explicit

Public bWORKING As Boolean
Public bKEEPWORKING As Boolean

Sub deja_vu()
    'never let it run on top of itself
    If bWORKING Then Exit Sub
    bWORKING = True

    'do something here; refresh connections or whatever

    Debug.Print Now 'just to show it did something

    If bKEEPWORKING Then _
        Application.OnTime Now + TimeSerial(0, 0, 5), "deja_vu"
    bWORKING = False
End Sub

bKEEPWORKING赋值为True并运行Deja_vu子过程。它会一直运行,直到您将bKEEPWORKING设置为False。有时,我可能会跳过bKEEPWORKING并让它在特定工作表单元格中查找值。如果值为0,则该过程不会重新安排自己。

答案 1 :(得分:1)

ThisWorkbook Module

Option Explicit
Private Sub Workbook_Open()
    Call StartTimer
End Sub

Private Sub Workbook_BeforeClose(Cancel As Boolean)
    Call StopTimer
End Sub

常规模块

Option Explicit
Dim RunTime

Sub StartTimer()
    Application.ScreenUpdating = False
    ActiveWorkbook.RefreshAll
    RunTime = Now + TimeValue("00:00:15")
    Application.OnTime RunTime, "RefreshTime"
    Application.ScreenUpdating = True
End Sub

Sub StopTimer()
'  http://www.cpearson.com/excel/OnTime.aspx
    On Error Resume Next
    Application.OnTime RunTime, "RefreshTime", Schedule:=False
    On Error GoTo 0
End Sub

Sub RefreshTime()
    ActiveWorkbook.Save
    StartTimer
End Sub