Search code examples
excelvba

Collecting data from various files -> files cannot be found within folder


I collect data from various Excel files and aggregate them within one "master file" with the code below.

This master file is in a folder other than the files I am trying to collect and aggregate.
Having saved the code, closed the Excel file and reopened it to check if it's working a second time, an error occurs.
That error states that a certain file cannot be found and the code stops immediately.

The line of code which is problematic:

With Workbooks.Open(Filename:=QuellDateiAktuell$)

Second question, that's solely nice to have, is there a possibility to name the sheets in the Excel file according to the last 15 digits of the files where the data comes from respectively?

Sub Collect Data ()
    Dim Folder$             ('this is where the aggregated data should be visible)
    Dim QuellDateien$, QuellDateiAktuell$ ('first one the folder where the data is at the moment; 
                                            the second one, each file with data within this current folder)
    Dim wbkZiel As Workbook

    With Application
        .ScreenUpdating = False
        .EnableEvents = False
    End With
        
    Folder$ = "W:\...\test.xlsm"
    QuellDateien$ = "W:\(every file in this last folder with the following ending:)\*.xlsb"
        
    'Open folder and open the first file from where the data should be collected
    Set wbkZiel = Workbooks.Open(Filename:=Folder$)
    QuellDateiAktuell$ = Dir(PathName:=QuellDateien$)

    'Loop to check, if there are other files
    Do Until Len (QuellDateiAktuell$) = 0

        'Open the files, copy Sheet1 and close the file
        
        '......AN ERROR OCCURS IN THE FOLLOWING, NAMELY "File cannot be found! ALTOUGH THERE IS A                         
         FILE ACTUALLY"......

        With Workbooks.Open(Filename:=QuellDateiAktuell$)
            .Sheets(1).Copy After:=wbkZiel.Sheets(1)
            .Close savechanges:=False
        End With

        'get the next folder and so on
        QuellDateiAktuell$ = Dir ()

    Loop

    With Application
        .ScreenUpdation = True
        .EnableEvents = True
    End With

End Sub

Solution

  • Dir returns just the file name and extension. You need to re-attach the directory path in order to open the file.

    Function FileOpen(ByVal Directory As String, ByVal Name_Format As String) As Workbook
        Dim FileName As String
        FileName = Dir(Directory & Name_Format)
        Set FileOpen = Application.Workbooks.Open(Directory & FileName) '<- I add the directory again
    End Function