让Excel VBA等待PowerQuery数据刷新继续

时间:2015-12-31 19:22:43

标签: excel vba wait

我的场景:我通过PowerQuery提取了一些数据表,我希望自动刷新数据,保存和关闭。我有一个任务调度程序每天凌晨1点运行它们。问题是Excel VBA在进入下一步(保存)之前不会等待PowerQuery更新。

有很多关于此的博客,我没有找到任何答案 - 但它让我找到了对我有用的东西!我并不为代码感到自豪,但在这里:

     Public Sub DataRefresh()

DisplayAlerts = False


For Each objConnection In ThisWorkbook.Connections
    'Get current background-refresh value
    bBackground = objConnection.OLEDBConnection.BackgroundQuery

    'Temporarily disable background-refresh
    objConnection.OLEDBConnection.BackgroundQuery = False

    'Refresh this connection
    objConnection.Refresh

    'Set background-refresh value back to original value
    objConnection.OLEDBConnection.BackgroundQuery = bBackground
Next



Workbooks("DA List.xlsm").Model.Refresh
DoEvents











For i = 1 To 100000
Worksheets("DA List").Range("G1") = i
Next i
DoEvents














ActiveWorkbook.Save
Application.Quit

End Sub

我认为这是有效的,因为除了数据刷新之外我给excel做了一些事情,DoEvents和我的下一步之间的额外线条似乎让VBA最终弄明白我的意图。

希望这会有所帮助!!

1 个答案:

答案 0 :(得分:1)

 Public Sub DataRefresh()

DisplayAlerts = False


For Each objConnection In ThisWorkbook.Connections
'Get current background-refresh value
bBackground = objConnection.OLEDBConnection.BackgroundQuery

'Temporarily disable background-refresh
objConnection.OLEDBConnection.BackgroundQuery = False

'Refresh this connection
objConnection.Refresh

'Set background-refresh value back to original value
objConnection.OLEDBConnection.BackgroundQuery = bBackground
Next



Workbooks("DA List.xlsm").Model.Refresh
DoEvents











For i = 1 To 100000
Worksheets("DA List").Range("G1") = i
Next i
DoEvents














ActiveWorkbook.Save
Application.Quit

End Sub