使用VBA刷新Excel中的查询

8fq7wneg  于 2023-01-18  发布在  其他
关注(0)|答案(1)|浏览(185)

长期读者,第一次提问者,
我有一个主文件,当我点击一个按钮将打开11个文件一个接一个刷新连接和关闭文件。然而,它没有刷新连接之前,它关闭文件。

Sub Task()

Workbooks.Open Filename:= "......sharepoint.com/sites/dummylocation/dummyfile.xlsx"

Dim WB As Workbook

Set WB = Application.Workbooks("dummy file.xlsx")
Dim ObjConnection As Variant
Dim bBackground As Variant

For Each ObjConnection In WB.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
WB.Close
End Sub

我已经能够通过注解“wb.cose”来找到它的错误,然后刷新就会工作。我想我需要某种延迟或其他什么?

rxztt3cl

rxztt3cl1#

我遇到了类似的问题,得到了多个解决方案here
对我来说,最有效的方法是添加这样一个函数:

Function WaitUntilFinish(Seconds As Double)
    Dim StopTime As Double: StopTime = Timer + Seconds
    Do While Timer < StopTime
        DoEvents
    Loop
End Function

然后在代码中使用它。我可以建议你在这里使用它吗?

'Refresh this connection
ObjConnection.Refresh
WaitUntilFinish (Seconds)
'Set background-refresh value back to original value
ObjConnection.OLEDBConnection.BackgroundQuery = bBackground

相关问题