8

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
Filip Ondo
  • 165
  • 1
  • 2
  • 12
  • Which Office you use? Btw, I'd recomment two things which may help: 1-give the name of a connection instead of ID (conn.Name), 2-do a Refresh before trying to remove the connection as it may still work, which is a possible reason the conn. is not dropped (to avoid data inconsistency) –  Nov 11 '13 at 10:13
  • I am using MS excel 2010, I refreshing it before killing connections – Filip Ondo Nov 11 '13 at 10:36
  • Using OLE or ODBC, or both? Because I would do this, as might help -guessing though- "for each conn in Actw.Conns.; ActiveWorkbook.Connections(conn.Name).ODBCConnection.Refresh; ActiveWorkbook.Connections(1).ODBCConnection.Delete next" (if it's ODBC) –  Nov 11 '13 at 10:42

2 Answers2

9

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
jacouh
  • 8,473
  • 5
  • 32
  • 43
6

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