在EXCEL vba中杀死连接

时间:2013-11-11 09:57:30

标签: excel vba excel-vba

我正在尝试从工作簿中删除连接,但我仍然在发送运行时错误5.我不知道该怎么做,因为在我的其他项目中它可以工作。

感谢您的建议。来自捷克共和国的问候。

    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。

上的错误
ActiveWorkbook.Connections.Item(i).Delete

2 个答案:

答案 0 :(得分:8)

您可以在for循环中尝试删除,使用VBA中的最小索引1(One = 2/2)代替i变量:

ActiveWorkbook.Connections.Item(1).Delete

而不是

ActiveWorkbook.Connections.Item(i).Delete

删除时,ActiveWorkbook.Connections.Count()会减少,有些.item(i)不再存在。

或者这个:

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

答案 1 :(得分:3)

为什么不使用连接集合的内置枚举器?

Public Sub DeleteAllConnectionsInWorkbook()
    Dim aConn as Object
    For Each aConn in ActiveWorkbook.Connections
        aConn.Delete
    Next aConn
End Sub