[RESOLVED] Using ADO and Querying Microsoft Excel Workbooks
Hello,
My questions are the following :
- I use VBA in Excel, and would like to use Excel itself as a data source (“Using ADO with Non-Standard Data Sources, Querying Microsoft Excel Workbooks”). I’d like to keep a table in excel and use SQL expression power to manipulate the data in the table (selection, grouping, filtering…), rather than using the usual Excel lookups.
- The table to query is located in the active workbook, as opposed to being saved in another, inactive, file.
- I then dump the SQL result in a range located in the Sheet1.
Here is the code I have:
VB Code:
Sub QueryXlSheet()
Dim RS As ADODB.Recordset
Dim ConnectionString As String
On Error GoTo ErrHandler
ConnectionString = _
"Provider=Microsoft.Jet.OLEDB.4.0;" & _
"Data Source=" & ThisWorkbook.FullName & ";" & _
"Extended Properties=Excel 8.0;"
Dim SQL As String
Dim TESTRNG As Range
'TESTRNG is an excel range name, which defines the table to query,
'with field names in the first, header row, and records in other rows.
The Microsoft Jet database engine could not find the object 'TESTRNG'. Make sure the object exists and that you spell its name and the path name correctly.
I do not know what went wrong. It could be great if you could put me on the right tracks.
Re: Using ADO and Querying Microsoft Excel Workbooks
Originally Posted by si_the_geek
To use Excel spreadsheets as tables, you need to enclose them inside [ $] , eg:
VB Code:
SQL = "SELECT * FROM [TESTRNG$]"
Thanks for the information.
I tried using the sheet name. For the code which i mentioned earlier i got "-1" for:
VB Code:
Debug.Print RS.RecordCount
What is the problem?
Originally Posted by si_the_geek
I don't think that you can use specific ranges tho, I think it has to be a whole sheet, eg:
VB Code:
SQL = "SELECT * FROM [" & ActiveSheet.name & "$]"
I think we can use specific ranges. But, I am not sure how to do that.
For example, If you look at the form option in Data menu, we can use the specific range to create forms. So, it is possible to work with specific range in excel.
Re: Using ADO and Querying Microsoft Excel Workbooks
Getting -1 for Recordcount means that the actual recordcount is unknown at that time, but it is greater than 0. You can either loop until EOF is true (quicker and easier), or use a client side cursor to get the recordcount (by specifying different parameters for Open).
For example, If you look at the form option in Data menu, we can use the specific range to create forms. So, it is possible to work with specific range in excel.
That is completely different.. here you are not dealing with Excel, you are dealing with ADO (which happens to be using an Excel file for the data).
It may be possible, but I dont know how you would do it, presumably something like this:
VB Code:
SQL = "SELECT * FROM [" & ActiveSheet.name & "$.A1:C3]"