Excel VBA runtime error 1004 - ThisWorkbook.Connections

Viewed 305

I've got a spreadsheet with multiple queries to an ODBC connection name of "CHECKMATE". In VBA "ThisWorkbook" object, I have the following VBA:

Private Sub Workbook_Open()
Dim TheConnectionName As String
For Each objWBConnect In ThisWorkbook.Connections
TheConnectionName = objWBConnect.Name
ThisWorkbook.Connections.Item(TheConnectionName).ODBCConnection.Connection = "ODBC;DSN=CHECKMATE"
Next objWBConnect
End Sub

This forces each ODBC connection in the worksheet to always use an ODBC connection name of CHECKMATE as this spreadsheet is distributed to multiple users where the IP address in the ODBC connection could be different but the name CHECKMATE is always consistent in every connection.

On this particular spreadsheet, I'm using Power Query to group two sets of data, remove duplicates and return the data to one of the worksheets where I'm summarizing information via VLOOKUP's and GETPIVOTDATA formulas. This is what's causing the runtime error 1004. I just need some help adjusting this code to account for the Power Query.

Thanks in advance for any help with this!

1 Answers

Untested, but I'm guessing you need to check the Type of the connection.

Also, using the .Name of the connection is unnecessary, i.e.

TheConnectionName = objWBConnect.Name
ThisWorkbook.Connections.Item(TheConnectionName)

is unnecessary since you can just refer to objWbConnect.

A simplified version of your code:

Private Sub Workbook_Open()
    Dim conn As WorkbookConnection
    For Each conn in ThisWorkbook.Connections
       If conn.Type = xlConnectionTypeODBC Then
           conn.ODBCConnection.Connection = "ODBC;DSN=CHECKMATE"
       End If
    Next
End Sub
Related