Forum Discussion
VBA to delete Power Query Connections or Folder
- Oct 17, 2022
JerryDNYC You need code like this to delete the queries:
Sub DelQueries() Dim q As WorkbookQuery For Each q In ActiveWorkbook.Queries If MsgBox("Delete query '" & q.Name & "'?", vbYesNo) = vbYes Then q.Delete End If Next End Sub
JKPieterse Is it possible to delete the queries within the active worksheet alone.
I tried using the below query, but it fails with error.
Sub Delete_Queries()
Dim q As WorkbookQuery
For Each q In ActiveSheet.Queries
sal_iv That requires a different approach:
Sub DelQueries()
Dim q As WorkbookQuery
Dim c As WorkbookConnection
For Each c In ActiveWorkbook.Connections
If c.Ranges.Count > 0 Then
If c.Ranges(1).Parent.Name = ActiveSheet.Name Then
c.Delete
End If
End If
Next
End Sub
- sal_ivFeb 08, 2023Copper Contributor
Thanks for the Quick response!!
For me the above quries doesn't remove the Queries in the worksheet.
In the Data & Connections pane, I can see I only have Queries. (Sorry I'm new to these.)
So I edited your code to the following.
```
Sub DelQueries()
Dim q As WorkbookQuery
Dim c As WorkbookConnection
For Each q In ActiveWorkbook.Queries
If q.Ranges.Count > 0 Then
If q.Ranges(1).Parent.Name = ActiveSheet.Name Then
q.Delete
End IfNext
End Sub
```
However, it errors out “Object doesn't support this property” for the line "If q.Ranges.Count > 0 Then"- JerryDNYCMar 07, 2023Copper ContributorThat is a VBA script, not a Query.
- JKPieterseFeb 08, 2023Silver ContributorCan you please post a screen-shot of your queries and connections pane?
The code sample I gave deletes all Queries which push their result to the active worksheet. I tested it and it works.- sal_ivFeb 08, 2023Copper Contributor
JKPieterse Much thanks for helping. PFB the screenshot.
As you can see, some are Connection-only and some are with tables. But I do not understand why the Connection-only do not appear in the Connections tab in the above screenshot.
It only appears in the Queries section.
Also I see that in your code you mention c.Delete. Isn't that deleting only connections. Shouldn't we doing q.Delete ?