Forum Discussion
Can the database name be easily changed from all ODBC queries in
Markku_E This can be done with VBA, but the level of difficulty will depend on a few things...
- Is the database (source) the same for each ODBC connection in the workbook?
- What type of ODBC connection is it (ie: SQL Server, MS Access Database, Excel Files, etc.)?
- Is the connection string the same for each ODBC connection in the workbook?
The first thing you might want to do is generate a list all ODBC connections in the workbook with their connection strings. To do this, try running the following code, which will output the list to the Immediate Window:
Sub PrintOdbcConnections()
Dim Item As WorkbookConnection
For Each Item In ActiveWorkbook.Connections
If Item.Type = xlConnectionTypeODBC Then
Debug.Print Item.Name & " | " & Item.ODBCConnection.Connection
End If
Next Item
End Sub
Note: to display the Immediate Window in Visual Basic, go to View > Immediate Window (or press Ctrl+G).
If ALL of the connection strings are the same for each ODBC connection in the workbook, the following code can be used to update each one by specifying a new connection string:
Sub UpdateOdbcConnections()
Dim Item As WorkbookConnection, newStr As String
newStr = "type the complete new connection string here"
For Each Item In ActiveWorkbook.Connections
If Item.Type = xlConnectionTypeODBC Then
Item.ODBCConnection.Connection = newStr
End If
Next Item
ActiveWorkbook.RefreshAll
End Sub
If they are not all the same, however, further code would need to be written to identify the differences and update each one accordingly. DO NOT run the above code without first confirming that ALL connection strings are the same. This is a very basic example only, intended to be used as a guide or starting point. Without knowing the specifics of your situation, this is as far as I can go at this time.
Some examples of what the connection strings might look like include:
'SQL Server:
newStr = "ODBC;DRIVER=SQL Server;SERVER=EXAMPLE;UID=admin;PWD=password;APP=Microsoft Office 2010;WSID=PC1"
'MS Access Database:
newStr = "ODBC;DSN=MS Access Database;DBQ=C:\Database\Test.accdb;DefaultDir=C:\Database;DriverId=25;FIL=MS Access;MaxBufferSize=2048;PageTimeout=5;"
'Excel Files:
newStr = "ODBC;DSN=Excel Files;DBQ=C:\Users\User\Desktop\Test.xlsx;DefaultDir=C:\Users\User\Desktop;DriverId=1046;MaxBufferSize=2048;PageTimeout=5;"