Delete all queries in a workbook

穿精又带淫゛_ 提交于 2019-12-23 18:13:33

问题


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


回答1:


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



回答2:


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


来源:https://stackoverflow.com/questions/49134863/delete-all-queries-in-a-workbook

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