How to reference and refresh a QueryTable in Excel 2016 in VBA

偶尔善良 提交于 2019-11-28 13:49:41

Query tables are a relic of older versions of Excel, before tables were a thing. Not sure how to even create one in Excel 2007+.

If you added your QT via the Data/Get External Data Ribbon menu, what you added was actually a ListObject.

I tested this on Sheet1, adding a simple query - Excel created the ListObject for me:

In the immediate pane, I get these results:

?Sheet1.QueryTables.Count
 0
?Sheet1.ListObjects.Count
 1

And I can reproduce your exact same error:

Sheet1.QueryTables(0).Refresh 'runtime error 1004

The error is simply outrageously misleading, that's all - it should really be an index out of bounds.

The solution is to refresh the ListObject instead:

Sheet1.ListObjects(1).Refresh 'works

You can access the underlying QueryTable object via the ListObject, too:

?Sheet1.ListObjects(1).QueryTable.CommandText 'gives you the query

You're seeing an error because the .Item method is base 1, not base 0

For example, this worked for me in Excel 2016:

Sheets("Roster Query").QueryTables(1).Refresh

So if you only have one QueryTable, it would be .QueryTables(1).

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!