Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Refer to QueryTable objects by name

Tags:

excel

vba

I am developing a MS Excel 2013 tool with VBA, which involves the use of QueryTables.

One inconvenience is accessing existing QueryTables within an Excel worksheet. Currently, the only method I can find to access a query table is by integer indexing. I came up with the following code for a quick proof of concept:

Sub RefreshDataQuery()

Dim querySheet As Worksheet
Dim interface As Worksheet

Set querySheet = Worksheets("QTable")
Set interface = Worksheets("Interface")

Dim sh As Worksheet
Dim QT As QueryTable

Dim startTime As Double
Dim endTime As Double

Set QT = querySheet.ListObjects.item(1).QueryTable

startTime = Timer
QT.Refresh
endTime = Timer - startTime

interface.Cells(1, 1).Value = "Elapsed time to run query"
interface.Cells(1, 2).Value = endTime
interface.Cells(1, 3).Value = "Seconds"

End Sub

This works, but I don't want to do it this way. The end product tool will have up to five different QueryTables. I want to refer to a QueryTable by its name.

How could I translate:

Set QT = querySheet.ListObjects.item(1).QueryTable

To something along the lines of:

Set QT = querySheet.ListObjects.items.QueryTable("My Query Table")
like image 490
Paul Renton Avatar asked Aug 05 '13 20:08

Paul Renton


1 Answers

This works:

Range("ClassifiedAsSupply").ListObject.QueryTable.Refresh BackgroundQuery:=True

Thanks to Dingbatdata: https://www.dingbatdata.com/2017/11/24/referencing-listobjects-with-vba/#comment-719

like image 57
Hans Schulze Avatar answered Sep 29 '22 14:09

Hans Schulze