Modify an embedded Connection String in microsoft excel macro

前端 未结 6 662
我在风中等你
我在风中等你 2020-12-14 19:01

I have an Excel document that has a macro which when run will modify a CommandText of that connection to pass in parameters from the Excel spreadsheet, like so:

6条回答
  •  予麋鹿
    予麋鹿 (楼主)
    2020-12-14 19:36

    I assume it is necessary for your to keep the same connection-name? Otherwise, it would be simplest to ignore it and create a new Connection.

    You might rename the connection, and create a new one using the name:

    ActiveWorkbook.Connections("Job_Cost_Code_Transaction_Summary").Name = "temp"
    'or, more drastic:
    'ActiveWorkbook.Connections("Job_Cost_Code_Transaction_Summary").Delete
    
    ActiveWorkbook.Connections.Add "Job_Cost_Code_Transaction_Summary", _
        "a description", "new connection string", "command text" '+ ,command type
    

    Afterwards, Delete this connection and reinstate the old connection/name. (I am unable to test this myself currently, so tread carefully.)

    Alternatively, you might change the current connections SourceConnectionFile:

    ActiveWorkbook.Connections("Job_Cost_Code_Transaction_Summary").OLEDBConnection.SourceConnectionFile = "..file location.."
    

    This typically references an .odc file (Office Data Connection) saved on your system that contains the connection details. You can create this file from the Window's Control Panel.

    You haven't specified, but an .odc file may be what your current connection is using.

    Again, I am unable to test these suggestions, so you should investigate further and take some precautions - so that you won't risk losing the current connection details.

提交回复
热议问题