I want to create a VBA program where it connects to the database you give it (hard coded). From here you are to program a cell to take the input for the WHERE clause in the query and then in a separate sheet it outputs the queried data. I do not want to filter this data, I need to query it. Can anyone help?
1 Answer
You can do this using Microsoft Query. The basic steps are:
1 - Connect to the database using Data>From Other Sources>Microsoft Query
2 - Modify the resulting query by right-cliking the resulting table and choosing Table>External Data Properties and clicking the little icon in the upper-corner. Then choose the Definition tab:

3 - Right-click the table and choose Parameters. In that dialog you can set cells to hold the parameters for the Where clauses.
For more info on this see this MSDN page and this Daily Dose post.
2 Comments
Mitchell Walker
So Doug, I did what you said there, and got that working. I ran a macro at the same time because I wanted to get VBA code so I can change it when I needed to. When I tried running the macro later I keep getting an error saying there is a run time error with the subscript out of range. When I click debug to show what is wrong it points me to this: With ActiveWorkbook.Connections("Query from ProductId").ODBCConnection.
Doug Glancy
It means that your connection name isn't "Query from ProductId." I'd guess it might now be "Query from ProductId2". This kind of programming isn't trivial, so you'll have to figure out a bunch of things like this. Based on this little bit of information, I'd suggest you program it to use the same connection every time, which would mean not adding a new one. That sounds obvious when I say it, so sorry if it's not much help.
Data>>Get External Datawhich can do this, so try recording a macro and see if you can modify it to do what you need.