在EXCEL vba中终止连接

我试图从我的工作簿中删除连接,但我仍然geting运行时错误5.我不知道该怎么做,因为在我的其他项目,它的工作原理。

谢谢你的build议。 来自捷克共和国的问候。

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 

你可以在for循环中使用VBA中的最小索引1(One = 2/2)来代替ivariables:

 ActiveWorkbook.Connections.Item(1).Delete 

代替

 ActiveWorkbook.Connections.Item(i).Delete 

当你删除,ActiveWorkbook.Connections.Count()将减less,一些.item(i)不存在。

或这个:

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

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

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