Instead of adding another query table using the add method, you can simply update the CommandText property of this connection. However, you should be aware that there is an error updating the CommandText property for an ODBC connection. If you temporarily switch to an OLEDB connection, update the CommandText property, and then return to ODBC, it will not create a new connection. Don't ask me why ... it just works for me.
Create a new module and paste the following code:
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
This UpdateWorkbookConnection routine UpdateWorkbookConnection works when updating OLEDB or ODBC connections. A join does not have to be associated with a pivot table. It also fixes another problem and allows you to update the connection, even if there are several pivot tables based on the same connection.
To initiate an update, simply call the function with the connection object and the command text parameters as follows:
UpdateWorkbookConnection ActiveWorkbook.Connections("Connection"), "exec sp_MyAwesomeProcedure"
You can also update the connection string.
source share