首页 > 解决方案 > 工作簿中的 VBA ADO 连接到同一工作簿

问题描述

我有一个工作簿,其中有一些 ADO 连接到同一个工作簿中的数据表,并且在建立连接时遇到问题,因为 Excel 在另一个实例中打开了我的工作簿。

字符串连接是:

"Provider=Microsoft.ACE.OLEDB.12.0;Data Source='" & ThisWorkbook.FullName & "';Extended Properties='Excel 12.0;HDR=YES;IMEX=1';"

有人可以帮我解决这个问题。

谢谢。

标签: excelvbaado

解决方案


采取以下功能

Function ConnectToXL(ByVal fileName As String)

Dim conn As New ADODB.Connection

    If Dir(fileName) = "" Then
        MsgBox "Could not find file " & fileName
        Exit Function
    End If

    Dim connectionString As String

    ' https://www.connectionstrings.com/access/
    connectionString = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" _
               & fileName & ";Extended Properties=""Excel 12.0;HDR=YES;"";"

    conn.Open connectionString

    Set ConnectToXL = conn

End Function

这是一段代码的示例如何使用它

   Dim xlCon As ADODB.Connection
    ' Connect to the workbook
    Set xlCon = ConnectToXL(ThisWorkbook.FullName)

是的,连接字符串与 OP 中发布的连接字符串没有太大区别。IMEX=1不应该造成任何伤害。这是为混合数据列检索数据的一种更安全的方法。


推荐阅读