繁体   English   中英

在Excel VBA中使用SQL访问其他Excel工作簿

[英]Use SQL in Excel VBA to access other Excel workbook

我正在尝试编写连接字符串和SQL脚本以在Excel中运行查询以从另一个Excel工作簿中提取数据。 这是我目前拥有的:

Sub Test()

   Dim conn As ADODB.Connection
   Dim rs As ADODB.Recordset
   Dim sConnString As String
   Dim sql As String

   ' Create the connection string.
   sConnString = "provider=Microsoft.Jet.OLEDB.4.0;data source=" & _
              "C:\Users\dblois\Desktop\Shareenas Report.xlsx" + ";Extended Properties=Excel 8.0;"

   ' Create the Connection and Recordset objects.
   Set conn = New ADODB.Connection
   Set rs = New ADODB.Recordset

   sql = "SELECT * FROM [Data$A1:AC73333]"

   ' Open the connection and execute.
   conn.Open sConnString
   Set rs = conn.Execute(sql)

   ' Check we have data.
   If Not rs.EOF Then
       ' Transfer result.
       Sheets(1).Range("A1").CopyFromRecordset rs
       ' Close the recordset
       rs.Close
   Else
       MsgBox "Error: No records returned.", vbCritical
   End If

   ' Clean up
   If CBool(conn.State And adStateOpen) Then conn.Close
   Set conn = Nothing
   Set rs = Nothing

End Sub

当我尝试打开连接时,我一直收到以下信息。 我的连接字符串出了什么问题?

外部表格的格式不正确

我发现以下内容 ,并将代码更改为:

sConnString = "provider=Microsoft.Jet.OLEDB.12.0;data source=" & _
                  "C:\Users\dblois\Desktop\Shareenas Report.xlsx" + ";Extended Properties=Excel 12.0;"

然后我收到以下错误:

找不到提供者。 可能不是属性安装

首次尝试时,您的OLEDB驱动程序不适用于Excel文件类型。 在第二次尝试中,您没有正确的OLEDB驱动程序,因为没有适用于Jet的12.0版本。 正如@Comintern在您发布的链接中的评论和答案一样,请使用ACE驱动程序版本。 但请注意,对于这两种类型,驱动程序的32/64位版本必须与您的MS Office位版本或您尝试连接到Excel数据源的任何其他程序,甚至语言(即PHP,Python,Java)相匹配。

对于较早的Excel .xls文件,您将使用Jet,因为此引擎尚不知道.xlsx格式,因此无法识别该文件类型:

strConnection = "Provider=Microsoft.JET.OLEDB.4.0;" _
                   & "Data Source='C:\Path\To\Excel.xls';" _
                   & "Extended Properties=""Excel 8.0;HDR=YES;"";"

对于最新的Excel文件(.xlsx,.xlsm,.xlsb),您将使用ACE,它也向后兼容.xls类型:

strConnection = "Provider=Microsoft.ACE.OLEDB.12.0;" _
                   & "Data Source='C:\Path\To\Excel.xlsx';" _
                   & "Extended Properties=""Excel 12.0 Xml;HDR=YES;"";"

或者,使用ODBC,它是许多程序(甚至是非Windows系统)用来连接到外部后端源的行业应用程序连接层。 甚至开放源代码编程语言也维护ODBC API,包括PHP的PDO,Python的pyodbc,R的RODBC。

对于较旧的源格式:

strConnection = "DRIVER={Microsoft Excel Driver (*.xls)};" _
                  & "DBQ=C:\Path\To\Excel.xlsx;"

对于较新的源格式:

strConnection = "DRIVER={Microsoft Excel Driver (*.xls, *.xlsx, *.xlsm, *.xlsb)};" _
                  & "DBQ=C:\Path\To\Excel.xlsx;"

驱动程序和位版本的相同原理也适用于MS Access .mdb与.accdb版本。

暂无
暂无

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

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