views:

194

answers:

2

We use MS Query to retrieve data from various databases to create management metrics (i.e. within Excel, go to Data...Import External Data...New Database Query). The SQL query and parameters (mostly conn string) are automatically stored by Excel within the spreadsheet.

However, we recently moved one of our databases to a new server. As a result, Excel prompts us for a new ODBC connection when trying to refresh the data, but it will not accept the new values. We can create new queries fine, so the ODBC connection is set up correctly, but we cannot change any queries.

Is there a way to programatically or otherwise change the IP address within these settings? I tried changing the xls file in a hex editor (the IP addresses are visible there), but it then says the workbook is corrupt.

+3  A: 

If you need to change the connection string of your queries, this macro will change it for all queries in the active workbook (you don't have to store the code in the workbook to be changed).

I include two sample connection strings - one supplies the dsn, one supplies the server/database. If your DSN is fine when creating new queries, try the DSN one first. Adjust SQL Server version if you use that one.

Also, one has standard security (uid,pwd) and the other uses windows-based security (trusted connection). Mix and match as appropriate.

Sub ChangeAddress()

Dim qt As QueryTable
Dim wks As Worksheet

Const strNEW_CONN_DSN As String = "ODBC;DSN=MyDSN;Description=MyDescription;UID=myid;PWD=mypwd;"

Const strNEW_CONN_SQL as String = "Driver={SQL Server Native Client 10.0};Server=myServerAddress;Database=myDB;Trusted_Connection=yes;"

For Each wks In ActiveWorkbook.Worksheets
    For Each qt In wks.QueryTables
        qt.Connection = strNEW_CONN_DSN
    Next qt
Next wks
End Sub
That worked, thx a lot!
Andrew
The question specified Excel 2003, but for anyone using Excel 2007, this code will not work. In 2007, you have to change ActiveWorkbook.Connections.ODBCConnection.Connection
A: 

I have the same issue with Excel 2007. I tried the code the "dendarii" added ActiveWorkbook.Connections.ODBCConnection.Connection . But it doesn't go through... Any idea how I fix this one?

Thanks, Mona

Mona