9

I am trying to write a sub to delete all queries in a workbook. I have got the code below:

Dim CN As Variant
Dim qTable As QueryTable



For Each CN In ThisWorkbook.Connections
    CN.Delete
Next CN

 For Each qTable In Sheets("Property Extract 1").QueryTables
qTable.Delete
Next qTable'

The connection deletion works fine but the queries remain. Any ideas how to delete all queries in a workbook?

I was planning to replicate the query deletion for 2 or 3 sheets.

thanks

braX
  • 11,506
  • 5
  • 20
  • 33
Chris
  • 182
  • 1
  • 1
  • 9
  • Posting this for anyone else stumbling onto this thread. I had a ss that over time became unresponsive and it ended up being that all the connections from web scraping were bogging it down. I used the code in this thread to delete all connections and the issue was fixed. Hopefully, this helps others with similar issues. – imnewhere Sep 11 '21 at 16:42

4 Answers4

13

First off, you cannot delete PQ Queries from VBA unless you are on Excel 2016/365. PQ is not exposed to VBA in earlier versions even when the add-on is installed. If you have the right version of Excel, you can delete the PQ Queries themselves just like you are clearing the connections:

Dim pq As Object
For Each pq In ThisWorkbook.Queries
    pq.Delete
Next
Wedge
  • 1,766
  • 1
  • 8
  • 14
3

Just add another loop to loop through sheets.

Dim cn
Dim qt As QueryTable
Dim ws As Worksheet
For Each cn In ThisWorkbook.Connections
    cn.Delete
Next
For Each ws In ThisWorkbook.Worksheets
    For Each qt In ws.QueryTables
        qt.Delete
    Next
Next ws

Edit: If you are adding using Query Wizard then perhaps you'd need modified code below.

Dim cn
Dim qt As QueryTable
Dim lo As ListObject
Dim ws As Worksheet
For Each cn In ThisWorkbook.Connections
    cn.Delete
Next
For Each ws In ThisWorkbook.Worksheets
    For Each qt In ws.QueryTables
        qt.Delete
    Next qt
    On Error Resume Next 'Ignore error if there's no query in table.
    For Each lo In ws.ListObjects
        lo.QueryTable.Delete
    Next lo
    On Error Goto 0
Next ws
shrivallabha.redij
  • 5,832
  • 1
  • 12
  • 27
2

Clear all connection in activeworkbook without any error. you must convert the Object to as String in order delete all connections

Sub ClearQueries()
    Dim pq As Object
    Dim q As String
    For Each pq In ThisWorkbook.Queries
        q = pq
        ActiveWorkbook.Queries(q).Delete
    Next
End Sub
David Buck
  • 3,752
  • 35
  • 31
  • 35
Tee
  • 21
  • 1
0

I Excel 2016 I was able to select all by maintaining CTRL and clicking on each in the Workbook queries pane. Then right-click --> Delete.

Guppy
  • 426
  • 5
  • 9