【问题标题】:Error when deleting connections from excel with VBA使用 VBA 从 excel 中删除连接时出错
【发布时间】:2019-03-28 17:19:58
【问题描述】:

我有以下代码:

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)':

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

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

【问题讨论】:

    标签: excel vba connection


    【解决方案1】:

    如果您想在循环中后退一步,则从最大值到最小值。您正试图将您的 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 代码甚至不会进入你的循环

    【讨论】:

      【解决方案2】:
      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
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2013-06-17
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2016-06-14
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多