2

I want to retrieve data from a closed workbook. My code is

fileName = "the path\test.xlsx"
With CreateObject("ADODB.Connection")
    .CommandTimeout = 500
    .ConnectionString = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" _
        & fileName & ";" & "Extended Properties=""Excel 12.0;HDR=YES;Readonly=true"";"
    .Open
      ThisWorkbooks.Worksheets("new").Range("A1").CopyFromRecordset .Execute("select * from [source$B1]")
    .Close
End With

I have some error, 424:object required, object doesn't found... I think it is a syntax problem. The purpose is to retrieve data from cells and put in the other sheet/workbook thanks for your help

11
  • I am not sure if it is the SQL, what line errors? Commented Jun 15, 2018 at 13:02
  • ThisWorkbooks.Worksheets("new").Range("A1").CopyFromRecordset .Execute("select * from [source$B1]") Commented Jun 15, 2018 at 13:12
  • Have you done any debugging? Like does the SQL return a recordset, is new a sheet? Is the connection open? Commented Jun 15, 2018 at 13:14
  • How can I know if the connection is open? There is no change on my sheet "new" Commented Jun 15, 2018 at 13:18
  • It is the right way to retrieve the value of the cell B1 (closed workbook, sheet "source") and put it in the cell A1 (current workbook, sheet "new") Commented Jun 15, 2018 at 13:22

1 Answer 1

1

Three things:

  1. Unless you defined "ThisWorkbooks" somewhere, I think it should be "ThisWorkbook".
  2. Using this method, I have only ever been able to fetch ranges that contain ":" in them, so change source$B1 to source$B1:B1.
  3. Since you only want one cell, you should turn the HDR (header) option off.

    fileName = "the path\test.xlsx"
    
    With CreateObject("ADODB.Connection")
        .CommandTimeout = 500
        .ConnectionString = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" _
        & fileName & ";" & "Extended Properties=""Excel 12.0;HDR=No;Readonly=true"";"
        .Open
        ThisWorkbook.Worksheets("new").Range("A1").CopyFromRecordset 
        .Execute("select * from [source$B1:B1]")
        .Close
    End With
    
Sign up to request clarification or add additional context in comments.

2 Comments

There is no error now, thanks a lot ! but nothing in the cell A1 of the "new" sheet. Maybe the request return nothing but there is a value in the cell B1 of the sheet "source"
@NCall Updated with a fix for HDR.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.