而不是使用add
方法添加另一个查询表,您可以简单地更新连接的CommandText属性。但是,您必须注意,在更新ODBC连接的CommandText
属性时存在错误。如果您临时切换到OLEDB连接,请更新您的CommandText
属性,然后切换回ODBC,它不会创建新连接。不要问我为什么......这只适用于我。
创建一个新的模块并插入下面的代码:
Option Explicit
Sub UpdateWorkbookConnection(WorkbookConnectionObject As WorkbookConnection, Optional ByVal CommandText As String = "", Optional ByVal ConnectionString As String = "")
With WorkbookConnectionObject
If .Type = xlConnectionTypeODBC Then
If CommandText = "" Then CommandText = .ODBCConnection.CommandText
If ConnectionString = "" Then ConnectionString = .ODBCConnection.Connection
.ODBCConnection.Connection = Replace(.ODBCConnection.Connection, "ODBC;", "OLEDB;", 1, 1, vbTextCompare)
ElseIf .Type = xlConnectionTypeOLEDB Then
If CommandText = "" Then CommandText = .OLEDBConnection.CommandText
If ConnectionString = "" Then ConnectionString = .OLEDBConnection.Connection
Else
MsgBox "Invalid connection object sent to UpdateWorkbookConnection function!", vbCritical, "Update Error"
Exit Sub
End If
If StrComp(.OLEDBConnection.CommandText, CommandText, vbTextCompare) <> 0 Then
.OLEDBConnection.CommandText = CommandText
End If
If StrComp(.OLEDBConnection.Connection, ConnectionString, vbTextCompare) <> 0 Then
.OLEDBConnection.Connection = ConnectionString
End If
.Refresh
End With
End Sub
这UpdateWorkbookConnection
子程序只能在更新OLEDB或ODBC连接。连接不一定必须链接到数据透视表。它还修复了另一个问题,即使存在多个基于同一连接的数据透视表,也可以更新连接。
启动更新只是使用连接对象和命令文本参数,像这样的功能:
UpdateWorkbookConnection ActiveWorkbook.Connections("Connection"), "exec sp_MyAwesomeProcedure"
您可以选择更新连接字符串为好。
当我尝试时,Worksheets(“Received”)...行给出了一个无效的过程调用运行时错误5.我也尝试将它从新连接更改为新的ADODB连接并相应地使用它。没有骰子。 – DavidStein 2011-02-08 14:46:58