Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Killing connection in EXCEL vba

Tags:

excel

vba

I am trying to removeconnection from my work book but I am still geting run-time error 5. I dont know what to do because in my other projects it works.

Thanks for advice. Greeting from czech Republic.

    Sub refresh_all()

    Dim i As Integer
    '~~> refresh workbook query
    Application.DisplayAlerts = False

    Workbooks("UAC_report_p.xlsb").Activate

    '~~> wait for refresh then execute Call save_as
    Do Until Application.CalculationState = xlDone
    DoEvents
    Loop

    ActiveWorkbook.RefreshAll

    Workbooks("UAC_report_p.xlsb").Activate

    '~~>kill all connections
        For i = 1 To ActiveWorkbook.Connections.Count
            If ActiveWorkbook.Connections.Count = 0 Then Exit For
            ActiveWorkbook.Connections.Item(i).Delete
            i = i - 1
        Next i

        Application.DisplayAlerts = True
    End Sub

P.S. getting error on

ActiveWorkbook.Connections.Item(i).Delete
like image 847
Filip Ondo Avatar asked Nov 11 '13 09:11

Filip Ondo


People also ask

How do I eliminate a connection in Excel?

Navigate to the Data Tab in the Excel Ribbon. Within the Queries & Connections button group, select the Edit Links Button. Select 1 or more Source Files from the Edit Link Dialog's Listbox. Click Break Link.


2 Answers

You could try this in the for loop for deleting, using the minimal index 1 (One = 2/2) in VBA in place of i variable:

ActiveWorkbook.Connections.Item(1).Delete

Instead of

ActiveWorkbook.Connections.Item(i).Delete

As you delete, ActiveWorkbook.Connections.Count() will diminish, Some .item(i) does no more exist.

Or this:

 '~~>kill all connections
    For i = ActiveWorkbook.Connections.Count To 1 Step -1
        ActiveWorkbook.Connections.Item(i).Delete
    Next
like image 111
jacouh Avatar answered Oct 02 '22 20:10

jacouh


Why not using the built-in enumerator of the connections collection?

Public Sub DeleteAllConnectionsInWorkbook()
    Dim aConn as Object
    For Each aConn in ActiveWorkbook.Connections
        aConn.Delete
    Next aConn
End Sub
like image 22
Espen Rosenquist Avatar answered Oct 02 '22 19:10

Espen Rosenquist