8

我正在尝试从我的工作簿中删除连接,但我仍然收到运行时错误 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

PS 出现错误

ActiveWorkbook.Connections.Item(i).Delete
4

2 回答 2

8

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

ActiveWorkbook.Connections.Item(1).Delete

代替

ActiveWorkbook.Connections.Item(i).Delete

当您删除时,ActiveWorkbook.Connections.Count() 将减少,Some .item(i) 不再存在。

或这个:

 '~~>kill all connections
    For i = ActiveWorkbook.Connections.Count To 1 Step -1
        ActiveWorkbook.Connections.Item(i).Delete
    Next
于 2013-11-11T13:14:09.960 回答
5

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

Public Sub DeleteAllConnectionsInWorkbook()
    Dim aConn as Object
    For Each aConn in ActiveWorkbook.Connections
        aConn.Delete
    Next aConn
End Sub
于 2017-01-04T11:50:27.803 回答