Question : How to automate adding a query to Excel 2007 spreadsheet?

I built a query generator to produce a complex query that needs to return results to an Excel 2007 spreadsheet.
I can run the query and dump the results into a spreadsheet, but I want to embed the query in the spreadsheet the same way as if MSQuery built it.
I want the user to save the spreadsheet and be able to update the data by right-clicking and choosing 'refresh data'.

The code below gives a 'parameter is invalid' error.
I tried many different variations for the 'connection string' parameter, from pure text, to the sqlconn object that I use later in the code that works.

Many hours searching the Internet yielded nothing than other people not able to get this to work.
Code Snippet:
1:
2:
excel.ActiveWorkbook.Connections.Add("Env Report", "New Report", ConfigurationManager.AppSettings("dev"), strQuery, CommandType.Text)
excel.ActiveWorkbook.RefreshAll()

Answer : How to automate adding a query to Excel 2007 spreadsheet?

Yes, that's what I said in my last post: "UID=root" is my username, with this you will not be able to open your table. Simply remove that and if you don't need the Workstation ID, remove "WSID=...", too (and in the first one, of course remove "Workstation ID=...").
In the connection string you never need to specify an attribute if you don't want to use it. The most of the other attributes are also not needed, only the macro recorder added them. I included them to be sure but for example "APP=Microsoft® Windows® Operating System" only tells the SQL Server which application name to display if you search the connection in the activity monitor.

Next is the DisplayName: It needs to be a name without spaces so "MatTrac_Report" would work. Naming conventions like names in Excel.

And: You can add the following line before the line with ".CommandText ..." in both cases:

.CommandType = Microsoft.Office.Interop.Excel.XlCmdType.xlCmdSql

This makes sure that the command is a query string, it works in both cases.

I saw that I mixed the buttons: ODC starts DSN and vice-versa...:)
Simply change that in the form or in the code.

In both cases it should run now after these changes. In my tests it works in any case.

Cheers,

Christian
Random Solutions  
 
programming4us programming4us