+ Reply to Thread
Results 1 to 3 of 3

Scan for files in sub folders, then append common cell value to end of summary list

Hybrid View

  1. #1
    Registered User
    Join Date
    09-17-2014
    Location
    Auckland NZ
    MS-Off Ver
    365
    Posts
    4

    Unhappy Scan for files in sub folders, then append common cell value to end of summary list

    Hi there, I am fairly new when it comes to VB coding, so please forgive my incompetence.
    I have tried my best by scouring the forums and Google to find anything could help. This is what I have come up with so far.

    I would like to to scan through the sub folders of a main directory to find all excel files, then copy the value of a merged cell C7:D7 in all them into to a list in the main file.
    This is like the consolidation codes that I have come across, but they only work on one folder. They do not scan through all sub folders from a directory to find other files.

    I would also like to work on closed workbooks to prevent macros and screen display from occurring.

    This is what I have managed so far. It scans through all of the folders and finds all of the excel files, and one by one, it appears to be copying the cell range to the summary sheet in my current workbook, but it is not paste them in main sheet correctly. It starts at A16 and I only ever get one row.

    I would like it to start at A1 and work its way down.

    Once I had the code working, I was looking at extending it to pull other cell values from the same sheets.

    My traget output was:

    Column 1 Column 2 Column 3
    Name Start_Date End_date
    (File 1 data)
    (File 2 data)


    Hopefully I have made this easy enough to understand.
    I am using Excel 2010

    Any help or guidance would be greatly appreciated.

    Sub test()
    
    Dim FSO As Object, fld As Object, Fil As Object
    Dim fsoFile As Object
    Dim fsoFol As Object
    Dim fileName As String
    
    Dim shtTemp As Worksheet
    Dim strFile As String
    Dim lngRow As Long
    
    
      Application.DisplayAlerts = False
    
    folderPath = "G:\test\"
        If Right(folderPath, 1) <> "\" Then folderPath = folderPath + "\"
             Set FSO = CreateObject("Scripting.FileSystemObject")
             Set fld = FSO.getfolder(folderPath)
        If FSO.folderExists(fld) Then
             For Each fsoFol In FSO.getfolder(folderPath).subfolders
                  For Each fsoFile In fsoFol.Files
                       If Mid(fsoFile.Name, InStrRev(fsoFile.Name, ".") + 1) = "xls*" Then
        fileName = fsoFile.Name
        Application.ScreenUpdating = False
        Application.EnableEvents = False
    
        'My file handling code
      lngRow = 1
      
        Set shtTemp = ActiveWorkbook.Sheets("Sheet1")
        
    
            Set wbkCS = Workbooks.Open(fsoFile.path)
    
    Dim nextRow As Integer
    
      nextRow = Sheets(1).Range("A" & Rows.Count).End(xlUp).Row + 1
    
        With wbkCS.Sheets(1)
        With .Range("C7:D7").Copy
        shtTemp.Range("A" & nextRow).PasteSpecial
        End With
        End With
        
    'Copy Sheet1!N20 to Column G
       'wbkCS.Sheets(1).Range("C").Copy Destination:=shtTemp(2).Range("B" & nextRow)
    
    
    
        wbkCS.Close SaveChanges:=False
      
       
    
    
    
    
                    End If
                  Next
             Next
       End If
    End Sub

  2. #2
    Forum Moderator Leith Ross's Avatar
    Join Date
    01-15-2005
    Location
    San Francisco, Ca
    MS-Off Ver
    2000, 2003, & 2010
    Posts
    23,259

    Re: Scan for files in sub folders, then append common cell value to end of summary list

    Hello sjanett,

    This should make things easier for you. I developed a macro to look for files in the main directory or any number of sub folders by name and type. All the code below can be placed in the same VBA module.

    Test1 Macro Code
    Sub Test1()
    
        Dim Files   As Variant
        Dim LastRow As Range
        Dim n       As Long
        Dim Wkb     As Workbook
        
        
            Set LastRow = ThisWorkbook.Worksheets("Sheet1").Cells(Rows.Count, "A").End(xlUp)
            
            n = GetFiles("G:\test\", Files, "*.xls*", -1)
            
            For n = 1 To UBound(Files)
                Set Wkb = Workbooks.Open(Files(n))
                Wkb.Worksheets("Sheeet1").Range("C7").Copy
                LastRow.Offset(n, 1).PasteSpecial Paste:=xlPasteAll
                Wkb.Close SaveChanges:=False
            Next n
            
    End Sub
    Macro to Search for Files
    '***************************************************************************************
    ' Written:  April 02, 2015                                                              )
    ' Author:   Leith Ross                                                                  )
    ' Summary:  List files using a filter and search the parent folder and subfolders.      )
    '                                                                                       )                                                                  )
    ' Arguments:                                                                            )
    '           Folder                                                                      )
    '               This is the path of the parent folder. The ending backslash             )
    '               is optional. E.G. "C:\Test\" and C:\Test" are seen the same.            )
    '                                                                                       )
    '           FileList                                                                    )
    '               A variant that will be converted to an 2 x n array that holds           )
    '               the Folder paths and File names. This variable must be declared         )
    '               prior to calling the function or an error will result.                  )
    '                                                                                       )
    '           FileFilter (Optional - default is "*.*" all files)                          )
    '               This controls the search parameters for the file names and              )
    '               extensions. The filter allows the use of wildcards characters           )
    '               "*" and "?". Multiple filters can be used at the same time by           )
    '               separating them with a semi-colon. E.G, "*.txt;*.csv". This will        )
    '               return all TEXT and CSV files.                                          )
    '                                                                                       )
    '           SubfolderDepth (Optional - default is 0)                                    )
    '               = 0 Searches only the Parent folder.                                    )
    '               = 1,2,3, etc. Sets the maximum number of subfodlers to search.          )
    '               = -1 Searches the parent folder and all the subfolders.                 )
    '                                                                                       )
    ' Return Value:                                                                         )
    '           The function returns the total number of files that match the filter.       )
    '                                                                                       )
    '***************************************************************************************
    
    Global FolderCnt    As Long
    Global oShell       As Object
    
    Function GetFiles(ByVal Folder As Variant, ByRef FileList As Variant, Optional ByVal FileFilter As String, Optional SubFolderDepth As Variant) As Long
    
        Dim Item    As Variant
        Dim LastCnt As Long
        Dim n       As Long
        Dim oFolder As Object
        Dim oItems  As Object
        
            If FileFilter = "" Then FileFilter = "*.*"
            
            If IsMissing(SubFolderDepth) Then SubFolderDepth = 0
            
            If oShell Is Nothing Then Set oShell = CreateObject("Shell.Application")
            
            Set oFolder = oShell.Namespace(Folder)
            
            If oFolder Is Nothing Then Exit Function
            
                Set oItems = oFolder.Items
                
                oItems.Filter 64, FileFilter
                
                If IsEmpty(FileList) Then
                    LastCnt = 0
                    ReDim FileList(1 To 2, 1 To oItems.Count)
                Else
                    LastCnt = UBound(FileList, 2)
                    ReDim Preserve FileList(1 To 2, 1 To LastCnt + oItems.Count)
                End If
                
                For Each Item In oItems
                    n = n + 1
                    FileList(1, LastCnt + n) = oFolder.Self.Path
                    FileList(2, LastCnt + n) = Item
                Next Item
                
                    If SubFolderDepth <> 0 Then
                        oItems.Filter 32, "*"
                        FolderCnt = FolderCnt + oItems.Count
                        
                        For Each Item In oItems
                            Call GetFiles(Item, FileList, FileFilter, SubFolderDepth - 1)
                        Next Item
                    End If
                
            GetFiles = UBound(FileList, 2)
                
    End Function
    Last edited by Leith Ross; 04-08-2015 at 10:16 PM.
    Sincerely,
    Leith Ross

    Remember To Do the Following....

    1. Use code tags. Place [CODE] before the first line of code and [/CODE] after the last line of code.
    2. Thank those who have helped you by clicking the Star below the post.
    3. Please mark your post [SOLVED] if it has been answered satisfactorily.


    Old Scottish Proverb...
    Luathaid gu deanamh maille! (Rushing causes delays!)

  3. #3
    Registered User
    Join Date
    09-17-2014
    Location
    Auckland NZ
    MS-Off Ver
    365
    Posts
    4

    Re: Scan for files in sub folders, then append common cell value to end of summary list

    Hi Leith,

    Thank you very much for you help. I have attempted to use your script, but it is being held up on
    If IsEmpty(FileList) Then
                    LastCnt = 0
                    ReDim FileList(1 To 2, 1 To oItems.Count)
    I receive a script out of range. is there something I am missing from the process?
    Do I have to define FileList before it is called as per your notes? and if so how can I do this.

    Your help is much appreciated.

    Cheers

+ Reply to Thread

Thread Information

Users Browsing this Thread

There are currently 1 users browsing this thread. (0 members and 1 guests)

Similar Threads

  1. Searching folders for list of files
    By joltremari in forum Excel Programming / VBA / Macros
    Replies: 2
    Last Post: 01-03-2014, 02:09 PM
  2. Replies: 0
    Last Post: 07-13-2012, 10:51 PM
  3. List files in folders in excel
    By jayblack in forum Excel Programming / VBA / Macros
    Replies: 11
    Last Post: 05-21-2010, 07:25 AM
  4. [SOLVED] Map/List of folders, subfolders & files
    By Bogdan in forum Excel Programming / VBA / Macros
    Replies: 5
    Last Post: 06-11-2006, 01:10 PM
  5. [SOLVED] Can anyone help me Create Excel list of files in windows folders
    By solrac1956 in forum Excel Formulas & Functions
    Replies: 1
    Last Post: 11-28-2005, 07:10 PM

Bookmarks

Posting Permissions

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

Search Engine Friendly URLs by vBSEO 3.6.0 RC 1