Excel作为数据库 - 查询超过65536行?

时间:2014-06-29 00:39:35

标签: sql excel vba

我正在尝试使用VBA查询电子表格,并且遇到了看似难以限制的65536行(尽管我正在运行Excel 2013)。 基本上,当尝试选择行数大于65536的所有行时,我收到以下错误消息:

运行时错误'-2147217865(80040e37)':

Microsoft Access数据库引擎找不到对象'Sheet1 $ A1:A65537'.....

我的代码如下:

Option Explicit

Sub ExcelQuery()

Dim conXLS As ADODB.Connection
Dim rsXLS As ADODB.Recordset
Dim strPath As String
Dim strSQL As String
Dim i As Integer



'Get the full directory + file name location of the current workbook (so it can query itself)'
strPath = Application.ActiveWorkbook.FullName

'create the ADO connection to the excel file'
Set conXLS = New ADODB.Connection
With conXLS
    .Provider = "Microsoft.ACE.OLEDB.12.0"
    .ConnectionString = "Data Source=" & strPath & ";" & _
    "Extended Properties=""Excel 12.0;HDR=Yes;IMEX=1;Readonly=False"""
End With
conXLS.Open

strSQL = "" & _
    "SELECT " & _
        "* " & _
    "FROM " & _
        "[Sheet1$A1:A65537] "

'create ADO recordset to hold contents of target sheet.'
Set rsXLS = New ADODB.Recordset
With rsXLS
    .CursorLocation = adUseClient
    .CursorType = adOpenForwardOnly
    .LockType = adLockReadOnly
End With

'using SQL return contents of the target sheet'
rsXLS.Open strSQL, conXLS

'disconnect the active connection'
Set rsXLS.ActiveConnection = Nothing

'Return results to excel'
Sheets("Sheet2").Cells(1, 1).CopyFromRecordset rsXLS

Set rsXLS = Nothing

'destroy the connection object'
conXLS.Close
Set conXLS = Nothing

End Sub

我也尝试了连接字符串:

With conXLS
    .Provider = "Microsoft.Jet.OLEDB.12.0"
    .ConnectionString = "Data Source=" & strPath & ";" & _
    "Extended Properties=Excel 12.0;"
    .Open

我已经设置了对“Microsoft ActiveX Data Objects 6.0 Library”和“OLE Automation”的引用。

有趣的是,使用MSQuery时似乎没有问题。

有没有人遇到过这个问题?

2 个答案:

答案 0 :(得分:7)

较旧的Excel版本(2007年之前)确实每个工作表限制大约65,000 +行。运行您的代码并引用任何从Excel 2007及更高版本开始的对象Lib(每个工作表最多1,048,576行,Lib版本相应地为12.x及以上)。与您的情况相关,请尝试使用符号[Sheet1$A:A]代替[Sheet1$A1:A65537] Rgds,

答案 1 :(得分:2)

我很久以前就遇到了这个问题。我所做的就是这样编写查询:

select Data from [Temp$]

其中 Temp 是我的工作表名称,单元格 A1 的内容是“数据”,而 A2:A80000 的内容是ids < / p>

有效。