Can't Remove Connections and Queries

nhandal

Board Regular
Joined
Apr 18, 2008
Messages
97
Hello,

I am using the following code to remove all connections and queries in a workbook, however, it does not work I still see all the connections and queries in the workbook, any idea why it is not working?

VBA Code:
Sub RemoveAllConnectionsAndQueryTables()

    Dim cn As Variant
    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 qt
    Next ws

End Sub

Thanks,
 

Excel Facts

How to fill five years of quarters?
Type 1Q-2023 in a cell. Grab the fill handle and drag down or right. After 4Q-2023, Excel will jump to 1Q-2024. Dash can be any character.
Give this a try:

VBA Code:
Sub ClearQueriesAndConnections()

    Dim wbCreated As Workbook
    Set wbCreated = ActiveWorkbook

    ' Delete all connections - Ken Puls
    Dim cn As WorkbookConnection

    For Each cn In wbCreated.Connections
        cn.Delete
    Next cn

    ' Delete all Queries
    Dim pq As Object
    Dim q As String

    For Each pq In wbCreated.Queries
        q = pq
        wbCreated.Queries(q).Delete
    Next

End Sub
 
Upvote 0
Solution

Forum statistics

Threads
1,224,823
Messages
6,181,176
Members
453,021
Latest member
Justyna P

We've detected that you are using an adblocker.

We have a great community of people providing Excel help here, but the hosting costs are enormous. You can help keep this site running by allowing ads on MrExcel.com.
Allow Ads at MrExcel

Which adblocker are you using?

Disable AdBlock

Follow these easy steps to disable AdBlock

1)Click on the icon in the browser’s toolbar.
2)Click on the icon in the browser’s toolbar.
2)Click on the "Pause on this site" option.
Go back

Disable AdBlock Plus

Follow these easy steps to disable AdBlock Plus

1)Click on the icon in the browser’s toolbar.
2)Click on the toggle to disable it for "mrexcel.com".
Go back

Disable uBlock Origin

Follow these easy steps to disable uBlock Origin

1)Click on the icon in the browser’s toolbar.
2)Click on the "Power" button.
3)Click on the "Refresh" button.
Go back

Disable uBlock

Follow these easy steps to disable uBlock

1)Click on the icon in the browser’s toolbar.
2)Click on the "Power" button.
3)Click on the "Refresh" button.
Go back
Back
Top