[Excel] External reference to closed workbooks

Solved
Sylvain -  
schoret Posted messages 6 Status Member -
Hello, I’m trying to read data from closed workbooks in order to consolidate the information into a single workbook. My goal is to have a dynamic reference, so I first tried with INDIRECT and CONCATENATE before discovering that INDIRECT is limited to open workbooks. I therefore found a VBA function LireCellule_ClasseurFerme() on the net to address this issue, but it returns the #VALUE error, and I even noticed that the function works if the workbook is open (which made me smile a little!). Could someone have an explanation that could help me move forward? Here is the function code:
Function LireCellule_ClasseurFerme( _ 
    Chemin As String, _ 
    Fichier As String, _ 
    Feuille As String, _ 
    Cellule As Variant) As Variant
    Application.Volatile
    Dim Source As Object, Rst As Object, ADOCommand As Object
    Dim Cible As String
    Feuille = Feuille & "$"
    Cible = Cellule.Address(0, 0, xlA1, 0) & ":" & _
            Cellule.Address(0, 0, xlA1, 0)
    Set Source = CreateObject("ADODB.Connection")
    Source.Open "Provider=Microsoft.Jet.OLEDB.4.0;" & _
        "Data Source=" & Chemin & "\" & Fichier & _
        ";Extended Properties=""Excel 8.0;HDR=No;"";"
    Set ADOCommand = CreateObject("ADODB.Command")
    With ADOCommand
        .ActiveConnection = Source
        .CommandText = "SELECT * FROM [" & Feuille & Cible & "]"
    End With
    Set Rst = CreateObject("ADODB.Recordset")
    '1 = , 3 =
    Rst.Open ADOCommand, , adOpenKeyset, adLockOptimistic
    Set Rst = Source.Execute("[" & Feuille & Cible & "]")
    LireCellule_ClasseurFerme = Rst(0).Value
    Rst.Close
    Source.Close
    Set Source = Nothing
    Set Rst = Nothing
    Set ADOCommand = Nothing
End Function
I did make sure to enable the Microsoft ActiveX Data Objects Library reference in the Visual Basic tools. Thanks for your help! Configuration: Windows XP / Firefox 3.6.12

5 answers

  1. Patrice33740 Posted messages 8400 Registration date   Status Member Last intervention   1 783
     
    We can read in a closed workbook with a simple formula:

    Sub LireFichierFermé()
    Dim NomFichier As String
    Dim Chemin As String
    Dim Formule As String
    ActiveSheet.Range("A1").ClearContents
    Chemin = "D:\Temp\"
    NomFichier = "Classeur_à_lire.xls"
    Formule = "=' " & Chemin & "[" & NomFichier & "]Feuil1" & "'! " & "A1"
    ActiveSheet.Range("A1").Formula = Formule
    ActiveSheet.Range("A1").Value = ActiveSheet.Range("A1").Value
    End Sub
    1
    1. schoret Posted messages 6 Status Member
       
      hey super big thanks for this little piece of code

      this does exactly the job I wanted

      it's been 2 days that I was looking for a solution to read closed files.

      thanks
      0