Delete all queries in a workbook

Chris picture Chris · Mar 6, 2018 · Viewed 10.4k times · Source

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

Answer

Wedge picture Wedge · Mar 8, 2018

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