In previous posts, I’ve discussed using VBA to extract connection information from Pivot Tables and hacking a tables command so that you can programmatically change the results of a query. But what if you have a table and you want to change its connection and its command?
This can be achieved pretty easy using the tables .QueryTable object. In fact, we can change the entire table using this class.
So how does it work? Suppose, I’ve inserted some data into a worksheet from SQL Server. The menu path is DATA à From Other Sources à From SQL Server. Next I get the familiar connection windows to connect to a server and then select a table (as below).
I’ll give the table a friendly name (adventure_works) and return the data to a table. I get a connected table which is sourced from a query and can be updated (either right click somewhere in the table and select Refresh from the popup menu or select the refresh button from the TABLE TOOLS à DESIGN (ribbon) menu).
I can also use the DESIGN of the table tools to give my table a decent name by just replacing its name (as in the following image).
Now I want to change the database server (and potentially the query) that my table uses. There are 2 things to keep in mind here. Firstly, we need to change the query’s connection string (no brainer eh) and secondly, the table (in Excel) was added as a table.
As in the previous post, I can refer to the table as a list object in VBA, this is a property of the sheet, so, in order to reference the table I’ll have to use some code like this (note the table was on Sheet2).
Dim li As ListObject
Set li = Sheet2.ListObjects(“aw_employees”)
For the connection string, I can refer to it through the ListObjects QueryTable class. So I could determine what the current connection string or set it by using the following code;
Debug.Print li.QueryTable.Connection ‘retrieve the connectionstring
li.QueryTable.Connection = “OLEDB;Provider=SQLOLEDB.1;…(this is my connection string) ..”
If I then refresh the table (using li.Refresh), one may think that’s the end of the story and our works completed – but that’s not quite true just yet.
Remember that we added the table as an SQL table? Because of this, the ‘query’ for the .querytable actually refers to a table including the SQL database and has its .CommandType as a table. If we debug the code to determine the command (as below) we could see this
After we change the connection, we could set the new table to use employee (without a database) with something simple (like);
li.QueryTable.CommandText = “dbo.DimEmployee”
Or, we could change the query type of an Command, and provide its text. This would suffice for that;
li.QueryTable.CommandType = xlCmdSql
li.QueryTable.CommandText = “select * from dbo.DimEmployee”
That’s about it, we can change the tables connection, its query and have these changes reflected in our table.