Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Querying more than 65536 rows error in Excel 2013

Tags:

sql

excel

vba

I am trying to query a spreadsheet using VBA and am running up against a seeming hard limit of 65536 rows (though I am running Excel 2013).

When trying to select all rows where the number of rows is greater than 65536 I get the following error message:

runtime error '-2147217865 (80040e37)':

The Microsoft Access database engine could not find the object 'Sheet1$A1:A65537'.....

My code:

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

I also tried the connection string:

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

I have set references to "Microsoft ActiveX Data Objects 6.0 Library" and "OLE Automation".

Interestingly, there seems to be no problem when using MSQuery.

like image 386
Nicholas Clarke Avatar asked Dec 14 '22 21:12

Nicholas Clarke


2 Answers

Older Excel versions (prior to 2007) indeed have a limit of some 65k+ rows per worksheet. Run your code and reference any object Lib starting w/Excel 2007 and up (max 1,048,576 rows per worksheet, Lib version correspondingly 12.x and up). Pertinent to your case, try to use a notation [Sheet1$A:A] instead of [Sheet1$A1:A65537] Rgds,

like image 197
Alexander Bell Avatar answered Dec 28 '22 14:12

Alexander Bell


I encountered this problem a long time ago. What I did was writing my query like this:

select Data from [Temp$]

Where Temp was my sheet name, the content of cell A1 was "Data" and the content of A2:A80000 were ids

It worked.

like image 43
Đức Thanh Nguyễn Avatar answered Dec 28 '22 14:12

Đức Thanh Nguyễn