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

前端 未结 8 710
北荒
北荒 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:23

    You should declare the connection as a separate object then you can close it once the database query is complete.

    I don't have the VBA IDE in front of me, so excuse me if there are any inaccuracies, but it should point you in the right direction.

    E.g.

    Dim SQL As String
    Dim con As connection
    
    Set con = New connection
    con.ConnectionString = "ODBC;DSN=DB01;UID=;PWD=;Database=MyDatabase"
    
    Worksheets("Received").QueryTables.Add(Connection:=con, Destination:=Worksheets("Received").Range("A5"), SQL:=SQL).Refresh
    
    con.close
    set con = nothing
    

提交回复
热议问题