Loop through Subfolders: Copy/Paste Cell Data

Fretflyer

New Member
Joined
Oct 3, 2012
Messages
8
Can someone get me pointed in the right direction on creating vba to loop through folders and subfolders to copy/paste data from a specific cell in multi-worksheet workbooks?

The cell is in the same place in all workbooks and is a named range/cell (jobnumber).
The workbooks have a standard ascending file name (C10, C11, C12 etc..) but each file is in a seperate folder, a few levels deep in the server directory.

Example directories
//server/jobs/c10/c10workbook
//server/jobs/c11/c11workbook

I hope that makes sense. Any help at all is much appreciated.
 

Excel Facts

Quick Sum
Select a range of cells. The total appears in bottom right of Excel screen. Right-click total to add Max, Min, Count, Average.
Thank you for the reply, I appreciate your time. I do have a few questions...
Unfortunately I cannot change the directory structure where the files are located and therefore will need to have this code look several levels deep. Will I be able to get the code to look that deep?
Can the code be changed to update an existing worksheet in the summary workbook instead of building a new one each time? I would like to be able to name fields and have the value be copied from the data files and pasted adjacent to the description.
I also would like to copy/paste several different cells. Do I need to copy/paste the code set for each cell I need to copied or can it be altered to copy/paste more than one cell?

I can't thank you enough for the help.

Here's what I am working with:

Code:
Sub MergeAllWorkbooks()
    Dim MyPath As String, FilesInPath As String
    Dim MyFiles() As String
    Dim SourceRcount As Long, FNum As Long
    Dim mybook As Workbook, BaseWks As Worksheet
    Dim sourceRange As Range, destrange As Range
    Dim rnum As Long, CalcMode As Long
    ' Change this to the path\folder location of your files.     *NO FILES FOUND IF THIS IS SET TO O:\Jobs WHICH IS WHERE IT WOULD NEED TO BE TO CATCH ALL NEEDED FILES
    MyPath = "O:\Jobs\Jobs In Progress\C12008 Meridian Apartments\Other" ' *IT DOES WORK AT THIS LOCATION, BUT ONLY FOR ONE FILE...
    ' Add a slash at the end of the path if needed.
    If Right(MyPath, 1) <> "\" Then
        MyPath = MyPath & "\"
    End If
    ' If there are no Excel files in the folder, exit.
    FilesInPath = Dir(MyPath & "*.xl*")
    If FilesInPath = "" Then
        MsgBox "No files found"
        Exit Sub
    End If
    ' Fill the myFiles array with the list of Excel files
    ' in the search folder.
    FNum = 0
    Do While FilesInPath <> ""
        FNum = FNum + 1
        ReDim Preserve MyFiles(1 To FNum)
        MyFiles(FNum) = FilesInPath
        FilesInPath = Dir()
    Loop
    ' Set various application properties.
    With Application
        CalcMode = .Calculation
        .Calculation = xlCalculationManual
        .ScreenUpdating = False
        .EnableEvents = False
    End With
    ' Add a new workbook with one sheet.    *WOULD LIKE TO APPEND TO ACTIVE SHEET*
   ' Set BaseWks = Workbooks.Add(xlWBATWorksheet).Worksheets(1)
   ' rnum = 1
   'Worksheets(Sheet1).Activate
   
    ' Loop through all files in the myFiles array.
    If FNum > 0 Then
        For FNum = LBound(MyFiles) To UBound(MyFiles)
            Set mybook = Nothing
            On Error Resume Next
            Set mybook = Workbooks.Open(MyPath & MyFiles(FNum))
            On Error GoTo 0
            If Not mybook Is Nothing Then
                On Error Resume Next
                ' Change this range to fit your own needs.   *NAMED CELLS = "JOBNUMBER", "PM" "FOREMAN" "CONTRACTAMOUNT" CAN I COPY PASTE MULTIPLE CELLS?
                With mybook.Worksheets(1)
                    Set sourceRange = .Range("jobnumber")
                End With
                If Err.Number > 0 Then
                    Err.Clear
                    Set sourceRange = Nothing
                Else
                    ' If source range uses all columns then
                    ' skip this file.
                    If sourceRange.Columns.Count >= BaseWks.Columns.Count Then
                        Set sourceRange = Nothing
                    End If
                End If
                On Error GoTo 0
                If Not sourceRange Is Nothing Then
                    SourceRcount = sourceRange.Rows.Count
                    If rnum + SourceRcount >= BaseWks.Rows.Count Then
                        MsgBox "There are not enough rows in the target worksheet."
                        BaseWks.Columns.AutoFit
                        mybook.Close savechanges:=False
                        GoTo ExitTheSub
                    Else
                        ' Copy the file name in column A.
                        With sourceRange
                            BaseWks.Cells(rnum, "A"). _
                                    Resize(.Rows.Count).Value = MyFiles(FNum)
                        End With
                        ' Set the destination range.
                        Set destrange = BaseWks.Range("B" & rnum)
                        ' Copy the values from the source range
                        ' to the destination range.
                        With sourceRange
                            Set destrange = destrange. _
                                            Resize(.Rows.Count, .Columns.Count)
                        End With
                        destrange.Value = sourceRange.Value
                        rnum = rnum + SourceRcount
                    End If
                End If
                mybook.Close savechanges:=False
            End If
        Next FNum
        'BaseWks.Columns.AutoFit
    End If
ExitTheSub:
    ' Restore the application properties.
    With Application
        .ScreenUpdating = True
        .EnableEvents = True
        .Calculation = CalcMode
    End With
End Sub
 
Upvote 0
Check out my links again, you can set subfolders to true

in my add-in you can also set different cells so start there
 
Upvote 0
I'm having a hard time getting it to select specific files. Can I set:

Get_File_Names("*Job Form")

in the portion of code below? I would like it to find files that end in "job form"

myCountOfFiles = Get_File_Names( _
MyPath:="O:\Jobs\", _
Subfolders:=True, _
ExtStr:="*.xl*", _
myReturnedFiles:=myFiles)

Thank you again, I see light at the end of the tunnel!!!
 
Upvote 0
Test this then

myCountOfFiles = Get_File_Names( _
MyPath:="O:\Jobs\", _
Subfolders:=True, _
ExtStr:="*Job Form.xl*", _
myReturnedFiles:=myFiles)
 
Upvote 0
Test this then

myCountOfFiles = Get_File_Names( _
MyPath:="O:\Jobs\", _
Subfolders:=True, _
ExtStr:="*Job Form.xl*", _
myReturnedFiles:=myFiles)
 
Upvote 0
That portion of it works great, Thank you!
My next step will be to try and get specific cells to copy to specific destination cells.

Am I correct that the section below will need to be edited to adjust copy/paste source and destination?


Code:
'Set the destination cell
                    If FileNameInA = True Then
                        Set destrange = BaseWks.Range("B" & rnum)
                        With SourceRange
                            BaseWks.Cells(rnum, "A"). _
                                    Resize(.Rows.Count).Value = myReturnedFiles(I)
                        End With
                    Else
                        Set destrange = BaseWks.Range("A" & rnum)
                    End If
                    'Copy/paste the data
                    If PasteAsValues = True Then
                        With SourceRange
                            Set destrange = destrange. _
                                            Resize(.Rows.Count, .Columns.Count)
                        End With
                        destrange.Value = SourceRange.Value
                    Else
                        SourceRange.Copy destrange
                    End If
                    rnum = rnum + SourceRcount
                End If
 
Upvote 0
Correct

But why not use my add-in you have a option there to fill in different cells and also filter on the file names
 
Upvote 0

Forum statistics

Threads
1,214,943
Messages
6,122,380
Members
449,080
Latest member
Armadillos

We've detected that you are using an adblocker.

We have a great community of people providing Excel help here, but the hosting costs are enormous. You can help keep this site running by allowing ads on MrExcel.com.
Allow Ads at MrExcel

Which adblocker are you using?

Disable AdBlock

Follow these easy steps to disable AdBlock

1)Click on the icon in the browser’s toolbar.
2)Click on the icon in the browser’s toolbar.
2)Click on the "Pause on this site" option.
Go back

Disable AdBlock Plus

Follow these easy steps to disable AdBlock Plus

1)Click on the icon in the browser’s toolbar.
2)Click on the toggle to disable it for "mrexcel.com".
Go back

Disable uBlock Origin

Follow these easy steps to disable uBlock Origin

1)Click on the icon in the browser’s toolbar.
2)Click on the "Power" button.
3)Click on the "Refresh" button.
Go back

Disable uBlock

Follow these easy steps to disable uBlock

1)Click on the icon in the browser’s toolbar.
2)Click on the "Power" button.
3)Click on the "Refresh" button.
Go back
Back
Top