简体   繁体   English

Excel VBA 运行时错误 1004 - ThisWorkbook.Connections

[英]Excel VBA runtime error 1004 - ThisWorkbook.Connections

I've got a spreadsheet with multiple queries to an ODBC connection name of "CHECKMATE".我有一个电子表格,其中包含对“CHECKMATE”的 ODBC 连接名称的多个查询。 In VBA "ThisWorkbook" object, I have the following VBA:在 VBA “ThisWorkbook” object 中,我有以下 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. 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.在这个特定的电子表格中,我使用 Power Query 对两组数据进行分组,删除重复项并将数据返回到其中一个工作表,我在其中通过 VLOOKUP 和 GETPIVOTDATA 公式汇总信息。 This is what's causing the runtime error 1004. I just need some help adjusting this code to account for the Power Query.这就是导致运行时错误 1004 的原因。我只需要一些帮助来调整此代码以解决 Power Query。

Thanks in advance for any help with this!提前感谢您对此的任何帮助!

Untested, but I'm guessing you need to check the Type of the connection.未经测试,但我猜您需要检查连接的Type

Also, using the .Name of the connection is unnecessary, ie此外,使用连接的.Name是不必要的,即

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

is unnecessary since you can just refer to objWbConnect .是不必要的,因为您可以参考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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM