Sunday, June 2, 2013

Refresh MS Query Without Selection

For years I've used macros to refresh queries in workbooks.  I originally recorded a macro to accomplish the refresh and it worked as expected but in order to refresh the data if the output of the query existed on a different sheet it was necessary to include in the macro a select of the worksheet, then select a cell in the query output.  With the sheet/cell selected the query is run and when the data has been refreshed the original worksheet is selected.  Here's an example of the macro:

Sub refresh1()

    Sheets("Sheet1").Select
    Range("A2").Select
    Selection.ListObject.QueryTable.refresh BackgroundQuery:=False
    Sheets("Sheet3").Select

End Sub

While this works fine and runs so quickly the selection of another worksheet and then selecting the original worksheet is usually not noticed by the user, however, it seemed to me there should be a better way of refreshing the data.

After a bit of Google searching I found that the above code could be replaced with this:

Sub refresh2()

    Sheets("Sheet1").Range("A2").ListObject.QueryTable.refresh BackgroundQuery:=False
    
End Sub

While this was obviously an improved solution I felt there could be a better way.  So back to Google an I found this:

Sub refresh3()

    ActiveWorkbook.Connections("BranchData").refresh

End Sub

In this code "BranchData" is the connection name of the query.

This is the best solution I've found to date.

No comments:

Post a Comment