1

Good Afternoon All,

I have been looking at various ways to change/update the data connection strings in a workbook to update the Server name only and keep the other parts of the string as they are.

Basically we have migrated servers and the server name has change and now we have a number of reports that need updating. Some have multiple connections as they connect to different databases.

I found a useful article but this replaces the string with a completely new one for all the data connections (which doesnt work due to the different databases) excel-macro-to-change-external-data-query-connections-e-g-point-from-one-data

Has anyone had to go through this process and found a way of easily updating the connection string?

Kind Regards

Community
  • 1
  • 1
TSQL_Newbie
  • 691
  • 2
  • 10
  • 19

2 Answers2

3

assuming the database names havent changed, but just the server, will the below work for you. Not tested

Sub ChangeAllConnections()

    Dim q As QueryTable, w As Worksheet, oldserverName As String, newServerName  As String
    Dim con As Variant

    oldserverName = "onlsrvr" 'Change here
    newServerName = "newsrvr" ' change here

    For Each w In ThisWorkbook.Worksheets
      For Each q In w.QueryTables
        q.Connection = Replace(q.Connection, oldserverName, newServerName)
      Next
    Next

    On Error Resume Next
     For Each con In ThisWorkbook.Connections
        con.ODBCConnection.Connection = Replace(con.ODBCConnection.Connection, oldserverName, newServerName)
        con.OLEDBConnection.Connection = Replace(con.OLEDBConnection.Connection, oldserverName, newServerName)
      Next
    On Error GoTo 0
End Sub
Krishna
  • 2,451
  • 1
  • 26
  • 31
1

I would consider placing things like this in an sameNameAsWorkbook.ini file. Keep the file in the same location as the Workbook. Then have your code read the ini file and build the connection that way. Then if it needs to change you can change it in one spot very easily.

MatthewD
  • 6,719
  • 5
  • 22
  • 41