工作簿中的VBA ADO连接到同一工作簿

问题描述 投票:-1回答:1

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

字符串连接为:

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

有人可以帮助我。

谢谢。

excel vba ado
1个回答
0
投票

执行以下功能

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不应造成任何伤害。这是一种检索混合数据列数据的更安全的方法。

© www.soinside.com 2019 - 2024. All rights reserved.