而不是使用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