Query Tables (QueryTables) in Excel 2010 with VBA with VBA creating many connections

前端 未结 8 715
北荒
北荒 2021-02-06 12:49

I\'m following code I found on another site. Here\'s the basics of my code:

Dim SQL As String
Dim connString As String

connString = \"ODBC;DSN=DB01;UID=;PWD=;Da         


        
8条回答
  •  孤独总比滥情好
    2021-02-06 13:27

    You might ask yourself why you're creating a QueryTable every time in your code. There are reasons to do it, but it usually isn't necessary.

    QueryTables are more typically design-time objects. That is, you create your QueryTable once (through code or the UI) and the you Refresh the QueryTable to get updated data.

    If you need to change the underlying SQL statement, you have some options. You could set up Parameters that prompt for a value or get it from a cell. Another option for changing the SQL is changing it in code for the existing QueryTable.

    Sheet1.QueryTables(1).CommandText = "Select * FROM ...."
    Sheet1.QueryTables(1).Refresh
    

    You can select different columns or even different tables by changing CommandText. If it's a different database, you'll need a new connection, but that's pretty rare.

    I know that doesn't answer your question directly, but I think determining whether you really need to add the QueryTable each time is the first step.

    For more on Parameters, see http://dailydoseofexcel.com/archives/2004/12/13/parameters-in-excel-external-data-queries/ It's for 2003, so there are few inconsistencies with later versions. The basics are the same, you just may need to learn about the ListObject object if you're using 2007 or later.

提交回复
热议问题