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

编程入门 行业动态 更新时间:2024-10-28 02:34:07
本文介绍了让 Excel VBA 等待 PowerQuery 数据刷新以继续的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

限时送ChatGPT账号..

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

My scenario : I have a few data tables pulled via PowerQuery that I wanted to have automatically refresh the data, save, and close. I had a task scheduler run these every day at 1 AM. The problem was that Excel VBA doesn't wait for the PowerQuery to update before it goes to the next step (save).

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

There are a LOT of blogs about this, I didn't find any answer - but it led me to something that worked for me! I'm not proud of the code but here it is:

     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 最终弄清楚了我的意图.

I think this works because I gave excel something to do other than the data refresh, and the extra lines between DoEvents and my next step seemed to make VBA finally figure out what I was intending.

希望这有帮助!!

推荐答案

 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 VBA 等待 PowerQuery 数据刷新以继续的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

更多推荐

[db:关键词]

本文发布于:2023-04-26 22:07:03,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1142868.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:数据   Excel   VBA   PowerQuery

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!