Results 1 to 9 of 9

Thread: [RESOLVED] Using ADO and Querying Microsoft Excel Workbooks

  1. #1

    Thread Starter
    Frenzied Member cssriraman's Avatar
    Join Date
    Jun 2005
    Posts
    1,465

    Resolved [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:
    1. Sub QueryXlSheet()
    2.     Dim RS As ADODB.Recordset
    3.     Dim ConnectionString As String
    4.  
    5.     On Error GoTo ErrHandler
    6.     ConnectionString = _
    7.     "Provider=Microsoft.Jet.OLEDB.4.0;" & _
    8.     "Data Source=" & ThisWorkbook.FullName & ";" & _
    9.     "Extended Properties=Excel 8.0;"
    10.  
    11.     Dim SQL As String
    12.     Dim TESTRNG As Range
    13. 'TESTRNG is an excel range name, which defines the table to query,
    14. 'with field names in the first, header row, and records in other rows.
    15.     Set TESTRNG = ActiveSheet.Range("A1:C6")
    16.     SQL = "SELECT * FROM TESTRNG;"
    17.     Set RS = New ADODB.Recordset
    18.     Call RS.Open(SQL, ConnectionString, CursorTypeEnum.adOpenForwardOnly, LockTypeEnum.adLockReadOnly, CommandTypeEnum.adCmdText)
    19.     Debug.Print RS.RecordCount
    20.  
    21. ErrHandler:
    22.     Debug.Print Err.Description
    23.     If (RS.State = ObjectStateEnum.adStateOpen) Then
    24.         RS.Close
    25.     End If
    26.     Set RS = Nothing
    27. End Sub
    I am getting the following error:

    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.

    Thanks in advance.
    CS

  2. #2
    Super Moderator si_the_geek's Avatar
    Join Date
    Jul 2002
    Location
    Bristol, UK
    Posts
    41,974

    Re: Using ADO and Querying Microsoft Excel Workbooks

    To use Excel spreadsheets as tables, you need to enclose them inside [ $] , eg:
    VB Code:
    1. SQL = "SELECT * FROM [TESTRNG$]"

    I don't think that you can use specific ranges tho, I think it has to be a whole sheet, eg:
    VB Code:
    1. SQL = "SELECT * FROM [" & ActiveSheet.name & "$]"

  3. #3

    Thread Starter
    Frenzied Member cssriraman's Avatar
    Join Date
    Jun 2005
    Posts
    1,465

    Re: Using ADO and Querying Microsoft Excel Workbooks

    Quote Originally Posted by si_the_geek
    To use Excel spreadsheets as tables, you need to enclose them inside [ $] , eg:
    VB Code:
    1. 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:
    1. Debug.Print RS.RecordCount
    What is the problem?
    Quote 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:
    1. 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.
    CS

  4. #4
    Super Moderator si_the_geek's Avatar
    Join Date
    Jul 2002
    Location
    Bristol, UK
    Posts
    41,974

    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:
    1. SQL = "SELECT * FROM [" & ActiveSheet.name & "$.A1:C3]"

  5. #5

    Thread Starter
    Frenzied Member cssriraman's Avatar
    Join Date
    Jun 2005
    Posts
    1,465

    Re: Using ADO and Querying Microsoft Excel Workbooks

    Here with I attached an sample excel sheet. In sheet 1, there are four columns: date, Category, id, rate.

    I want do some sql queries on that for example i need to calculate the total value of rate column where the date is "2/1/2006".

    Somebody please look into that and help me out.

    Thanks in advance.
    Attached Files Attached Files
    CS

  6. #6
    Super Moderator si_the_geek's Avatar
    Join Date
    Jul 2002
    Location
    Bristol, UK
    Posts
    41,974

    Re: Using ADO and Querying Microsoft Excel Workbooks

    As you have headers in your sheet, you need to specify that in your connection string, ie:
    VB Code:
    1. ConnectionString = _
    2.     "Provider=Microsoft.Jet.OLEDB.4.0;" & _
    3.     "Data Source=" & ThisWorkbook.FullName & ";" & _
    4.     "Extended Properties=[u]""Excel 8.0;HDR=Yes;""[/u]"
    You can then use SQL to reference the fields, eg:
    VB Code:
    1. SQL = "SELECT Sum(Rate) " _
    2.             & "FROM [Sheet1$] " _
    3.             & "WHERE [date] = '2/1/2006' "

  7. #7

    Thread Starter
    Frenzied Member cssriraman's Avatar
    Join Date
    Jun 2005
    Posts
    1,465

    Re: Using ADO and Querying Microsoft Excel Workbooks

    Si, Thanks for helping me.

    I got the error: "Data type mismatch in criteria expression."

    Here is the complete code with the changes:
    VB Code:
    1. Sub QueryXlSheet2()
    2.     Dim RS As ADODB.Recordset
    3.     Dim ConnectionString As String
    4.  
    5.     On Error GoTo ErrHandler
    6.     ConnectionString = "Provider=Microsoft.Jet.OLEDB.4.0;" & _
    7.     "Data Source=" & ActiveWorkbook.FullName & ";" & _
    8.     "Extended Properties=""Excel 8.0;HDR=Yes;"""
    9.     Dim SQL As String
    10.     SQL = "SELECT Sum(Rate) " _
    11.             & "FROM [Sheet1$] " _
    12.             & "WHERE [date] = '2/1/2006' "
    13.     Set RS = New ADODB.Recordset
    14.     RS.Open SQL, ConnectionString, CursorTypeEnum.adOpenForwardOnly, LockTypeEnum.adLockReadOnly, CommandTypeEnum.adCmdText ' -> Error on this line
    15.     Debug.Print RS.RecordCount
    16.     Debug.Print RS(0)
    17.  
    18. ErrHandler:
    19.     Debug.Print Err.Description
    20.     If (RS.State = ObjectStateEnum.adStateOpen) Then
    21.         RS.Close
    22.     End If
    23.     Set RS = Nothing
    24. End Sub
    Please help me.

    Thanks,
    CS

  8. #8
    Ex-Super Mod RobDog888's Avatar
    Join Date
    Apr 2001
    Location
    LA, Calif. Raiders #1 AKA:Gangsta Yoda™
    Posts
    60,709

    Re: Using ADO and Querying Microsoft Excel Workbooks

    If your column [date] is formatted as a Date data type in Excel then the query criteria will need to compare a like type, date.
    VB Code:
    1. & "WHERE [date] = #2/1/2006# "
    VB/Office Guru™ (AKA: Gangsta Yoda®)
    I dont answer coding questions via PM. Please post a thread in the appropriate forum.

    Microsoft MVP 2006-2011
    Office Development FAQ (C#, VB.NET, VB 6, VBA)
    Senior Jedi Software Engineer MCP (VB 6 & .NET), BSEE, CET
    If a post has helped you then Please Rate it!
    Reps & Rating PostsVS.NET on Vista Multiple .NET Framework Versions Office Primary Interop AssembliesVB/Office Guru™ Word SpellChecker™.NETVB/Office Guru™ Word SpellChecker™ VB6VB.NET Attributes Ex.Outlook Global Address ListAPI Viewer utility.NET API Viewer Utility
    System: Intel i7 6850K, Geforce GTX1060, Samsung M.2 1 TB & SATA 500 GB, 32 GBs DDR4 3300 Quad Channel RAM, 2 Viewsonic 24" LCDs, Windows 10, Office 2016, VS 2019, VB6 SP6

  9. #9

    Thread Starter
    Frenzied Member cssriraman's Avatar
    Join Date
    Jun 2005
    Posts
    1,465

    Re: Using ADO and Querying Microsoft Excel Workbooks

    Thanks Rob! it worked fine.

    Here is the complete code:
    VB Code:
    1. Sub QueryXlSheet2()
    2.     Dim RS As ADODB.Recordset
    3.     Dim ConnectionString As String
    4.  
    5.     On Error GoTo ErrHandler
    6.     ConnectionString = "Provider=Microsoft.Jet.OLEDB.4.0;" & _
    7.                        "Data Source=" & ActiveWorkbook.FullName & ";" & _
    8.                        "Extended Properties=""Excel 8.0;HDR=Yes;"""
    9.     Dim SQL As String
    10.     'SQL = "SELECT Sum(Rate) " _ ' using Sum function in query
    11.     SQL = "SELECT date, Category, id, Rate " _
    12.         & "FROM [Sheet1$] " _
    13.         & "WHERE [Rate] = 12 "    'Number
    14.     '& "WHERE [Category] = 'Fruits' " 'String
    15.     '& "WHERE [date] = #2/1/2006# " 'Date
    16.     Set RS = New ADODB.Recordset
    17.     'RS.Open SQL, ConnectionString, CursorTypeEnum.adOpenForwardOnly, LockTypeEnum.adLockReadOnly, CommandTypeEnum.adCmdText
    18.     RS.Open SQL, ConnectionString, 1, 1, 1
    19.     'Debug.Print RS.RecordCount
    20.     'Debug.Print RS(0)
    21.     Do While Not RS.EOF
    22.         'Debug.Print RS(0)
    23.         MsgBox RS(0)
    24.         'MsgBox RS(0) & " " & RS(1) & " " & RS(2) & " " & RS(3)
    25.         RS.MoveNext
    26.     Loop
    27.  
    28. ExitHere:
    29.     If (RS.State = ObjectStateEnum.adStateOpen) Then
    30.         RS.Close
    31.     End If
    32.     Set RS = Nothing
    33.     Exit Sub
    34.  
    35. ErrHandler:
    36.     Debug.Print Err.Description
    37.     GoTo ExitHere
    38. End Sub
    CS

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •  



Click Here to Expand Forum to Full Width