0

我有以下代码:

Sub deletedconns()
For i = 1 To ActiveWorkbook.Connections.Count
If ActiveWorkbook.Connections.Count = 0 Then Exit Sub
ActiveWorkbook.Connections.Item(i).Delete
i = i - 1
Next i
End Sub

当我尝试使用 sub 时,出现此错误:

运行时错误“-2147417848 (80010108)”:

自动化错误 调用的对象已与其客户端断开连接。

问题是,我要么需要删除连接,要么只能更改路径。我尝试编辑连接,但它也改变了分隔符的选择,把一切都搞砸了。

4

2 回答 2

0

如果您想在循环中后退一步,则从最大值到最小值。你试图强迫你i超出它的声明范围

Sub deletedconns()
    Dim i As Long
    For i = ActiveWorkbook.Connections.Count To 1 Step -1
        ActiveWorkbook.Connections.Item(i).Delete
    Next i
End Sub

您也可以删除您的If ActiveWorkbook.Connections.Count = 0 Then Exit Sub线路。如果ActiveWorkbook.Connections.Count = 0代码甚至不会进入你的循环

于 2019-03-28T17:23:13.010 回答
0
Option Explicit

Sub deletedconns()

    Dim i As Long '<- You forgot to declare i

    With ThisWorkbook

        For i = .Connections.Count To 1 Step -1 '<- When we delete you good backwards
            'There is no need to check if connections are 0. if are zero the code would not get in the loop
        '                If .Connections.Count = 0 Then
        '                    Exit Sub
        '                Else
        '                    .Connections.Item(i).Delete
        '                End If '<- You forgot end if

        Next i

    End With

End Sub
于 2019-03-28T17:58:45.133 回答