Closed Thread
Results 1 to 10 of 10

Combine multiple workbooks into one single workbook

Hybrid View

maacmaac Combine multiple workbooks... 02-22-2010, 12:43 AM
JBeaucaire Re: Combine multiple... 02-22-2010, 03:29 AM
maacmaac Re: Combine multiple... 02-23-2010, 12:22 AM
umesh_uvg Re: Combine multiple... 02-23-2010, 06:49 PM
jabryantiii Re: Combine multiple... 02-23-2010, 07:51 PM
JBeaucaire Re: Combine multiple... 02-23-2010, 08:16 PM
maacmaac Re: Combine multiple... 02-23-2010, 09:03 PM
JBeaucaire Re: Combine multiple... 02-23-2010, 09:19 PM
maacmaac Re: Combine multiple... 02-23-2010, 09:29 PM
JBeaucaire Re: Combine multiple... 02-23-2010, 09:38 PM
  1. #1
    Valued Forum Contributor
    Join Date
    11-20-2003
    MS-Off Ver
    2010, 2016
    Posts
    1,176

    Combine multiple workbooks into one single workbook

    I am trying to combine ~300 workbooks into one single workbook. All 300 workbooks have the exact same header. I tried using the code from thread https://www.excelforum.com/showthread.php?p=696435 but nothing is being copied over. The only difference between my example and the other is I only need to take data from the first sheet in each data workbook. All the workbooks are located in following directory
     F:\Excel Tips\Combine Workbooks\WorkbookData
    The “master file” is located in another directory. The “master file” also has the same header as the data workbooks. Basically, I want to retrieve all data (excluding the header) from the first data workbook and copy to the master file. Then I want to go to the second workbook and retrieve all data from the second data workbook and copy to master file, and so on. The code I am using to combine is as follows:
     Sub Get_Value_From_All()
        Dim wbSource As Workbook
        Dim wbThis As Workbook
        Dim rToCopy As Range
        Dim uRng   As Range
        Dim rNextCl As Range
        Dim lCount As Long
        Dim bHeaders As Boolean
        Dim Firstrow As Long
        Dim Lastrow As Long
        Dim Lrow   As Long
        Dim CalcMode As Long
        Dim ViewMode As Long
    
        With Application
            .ScreenUpdating = False
            .DisplayAlerts = False
            .EnableEvents = False
    
            On Error Resume Next
    
            Set wbThis = ThisWorkbook
            'clear the range except  headers
            Set uRng = wbThis.Worksheets(1).UsedRange
            If uRng.Cells.Count <= 1 Then
                'no data in master sheet
                bHeaders = False
                GoTo search
            End If
            uRng.Offset(1, 0).Resize(uRng.Rows.Count - 1, _
                                     uRng.Columns.Count).Clear
    search:
            With .FileSearch
                .NewSearch
                'Change path to suit
                .LookIn = "F:\Excel Tips\Combine Workbooks\WorkbookData"
                .FileType = msoFileTypeExcelWorkbooks
    
                If .Execute > 0 Then    'Workbooks in folder
                    For lCount = 1 To .FoundFiles.Count    ' Loop through all.
                        'Open Workbook x and Set a Workbook  variable to it
                        Set wbSource = Workbooks.Open(Filename:=.FoundFiles(lCount), UpdateLinks:=0)
                        For i = 1 To Sheets.Count - 1
                            Set rToCopy = wbSource.Worksheets(i).UsedRange
                            Set rNextCl = wbThis.Worksheets(1).Cells(Rows.Count, 1).End(xlUp).Offset(1, 0)
                            If bHeaders Then
                                'headers exist so don't copy
                                rToCopy.Offset(1, 0).Resize(rToCopy.Rows.Count - 1, _
                                                            rToCopy.Columns.Count).Copy rNextCl
                                'no headers so copy
                                'place headers in Row 2
                            Else: rToCopy.Copy Cells(1, 1)
                                bHeaders = True
                            End If
                        Next i
                        wbSource.Close False     'close source workbook
                    Next lCount
                Else: MsgBox "No workbooks found"
                End If
            End With
    
            CalcMode = .Calculation
            .Calculation = xlCalculationManual
        End With
    'not checked following code
                With ActiveSheet
                    .Select
        
                    ViewMode = ActiveWindow.View
                    ActiveWindow.View = xlNormalView
        
                    .DisplayPageBreaks = False
        
                    Firstrow = .UsedRange.Cells(1).Row
                    Lastrow = .UsedRange.Rows(.UsedRange.Rows.Count).Row
                    For Lrow = Lastrow To Firstrow Step -1
                        With .Cells(Lrow, "A")
                            If Not IsError(.Value) Then
                                If .Value = "" Then .EntireRow.Delete
                            End If
                        End With
                    Next Lrow
                End With
                On Error GoTo 0
                ScreenUpdating = True
                DisplayAlerts = True
                EnableEvents = True
            'End With
    End Sub
    Thank you in advance for any assistance.
    Last edited by maacmaac; 02-23-2010 at 09:29 PM.

  2. #2
    Forum Expert JBeaucaire's Avatar
    Join Date
    03-21-2004
    Location
    Bakersfield, CA
    MS-Off Ver
    2010, 2016, Office 365
    Posts
    33,492

    Re: Combine multiple workbooks into one single workbook

    FileSearch doesn't work in Excel 2007, so to have a method that will work in all your Excel versions, try this macro of mine I use for this very task.

    The only additional thing you would need to do is create a folder called "Imported" inside the folder with the files, the macro will import the data and move the files to the imported folder so there's no chance they'll be imported again if you run it a second time.

    OR...delete the two lines of code that say "Optional" and that part will go away.

    Option Explicit
    
    Sub Consolidate()
    'Author:     JBeaucaire'
    'Date:       9/15/2009     (2007 compatible)'
    'Summary:    Open all Excel files in a specific folder and merge data'
    '            into one master sheet (stacked)'
    '            Moves imported files into another folder'
    Dim fName As String, fPath As String, fPathDone As String, OldDir As String
    Dim LR As Long, NR As Long
    Dim wbkOld As Workbook, wbkNew As Workbook, ws As Worksheet
    
    'Setup
        Application.ScreenUpdating = False
        Application.EnableEvents = False
        Application.DisplayAlerts = False
        
        Set wbkNew = ThisWorkbook
        wbkNew.Activate
        Sheets("Master").Activate   'sheet report is built into...edit to match
        
        If MsgBox("Import new data to this report?", vbYesNo) = vbNo Then Exit Sub
        
        If MsgBox("Clear the old data first?", vbYesNo) = vbYes Then
            Range("A2:A" & Rows.Count).EntireRow.ClearContents
            NR = 2
        Else
            NR = Range("A" & Rows.Count).End(xlUp).Row + 1
        End If
    
    'Path and filename
        OldDir = CurDir             'memorizes the user's current working path
        fPath = "F:\Excel Tips\Combine Workbooks\WorkbookData\"
        fPathDone = "F:\Excel Tips\Combine Workbooks\WorkbookData\Imported]"   'optional
        ChDir fPath
        fName = Dir("*.xl*")      'filtering key, change to suit
    
    'Import a sheet from found file
        Do While Len(fName) > 0
            'Open file
                Set wbkOld = Workbooks.Open(fName)
            'Find last row and copy data
                Sheets(1).Activate
                LR = Range("A" & Rows.Count).End(xlUp).Row   'find the bottom row of data...change to a different column if "A" isn't reliable for spotting this value
                Range("A1:A" & LR).EntireRow.Copy _
                    wbkNew.Sheets("Master").Range("A" & NR)
            'close file
                wbkOld.Close False
            'Next row
                NR = Range("A" & Rows.Count).End(xlUp).Row + 1
            'move file to "imported" folder
                Name fPath & fName As fPathDone & fName         'optional
            'ready next filename
                fName = Dir
        Loop
    
    'Cleanup
        ActiveSheet.Columns.AutoFit
        Application.DisplayAlerts = True
        Application.EnableEvents = True
        Application.ScreenUpdating = True
    
    'restores user's original working path
        ChDir OldDir
    End Sub
    Last edited by JBeaucaire; 02-22-2010 at 03:32 AM.
    _________________
    Microsoft MVP 2010 - Excel
    Visit: Jerry Beaucaire's Excel Files & Macros

    If you've been given good help, use the icon below to give reputation feedback, it is appreciated.
    Always put your code between code tags. [CODE] your code here [/CODE]

    ?None of us is as good as all of us? - Ray Kroc
    ?Actually, I *am* a rocket scientist.? - JB (little ones count!)

  3. #3
    Valued Forum Contributor
    Join Date
    11-20-2003
    MS-Off Ver
    2010, 2016
    Posts
    1,176

    Re: Combine multiple workbooks into one single workbook

    I am running the code line-by-line. It is going through the code fine and copying data from each book and pasting it into the MasterCombine workbook. However, when it gets the last workbook, everything is deleted and it reverts back to the original file with original data. It appears to be crapping out when it gets to command that opens file.
            'Open file
                Set wbkOld = Workbooks.Open(fName)
    I can't for the life of me figure out what is wrong. Any help is appreciated. I am trying the code in Excel 2003.

    I have all the data in one path, which is "G:\Excel Tips\Combine Workbooks\WorkbookData\" The files are:
    Book1
    Book2
    Book3
    Book4
    Book5
    MasterCombine (contains code to combine Book 1-5)

    I have another path, which is "G:\Excel Tips\Combine Workbooks\WorkbookData\Import\"
    This folder is empty.
    Sub Consolidate()
    'Author:     JBeaucaire'
    'Date:       9/15/2009     (2007 compatible)'
    'Summary:    Open all Excel files in a specific folder and merge data'
    '            into one master sheet (stacked)'
    '            Moves imported files into another folder'
    Dim fName As String, fPath As String, fPathDone As String, OldDir As String
    Dim LR As Long, NR As Long
    Dim wbkOld As Workbook, wbkNew As Workbook, ws As Worksheet
    
    'Setup
        Application.ScreenUpdating = False
        Application.EnableEvents = False
        Application.DisplayAlerts = False
        
        Set wbkNew = ThisWorkbook
        wbkNew.Activate
        Sheets("Master").Activate   'sheet report is built into...edit to match
        
        If MsgBox("Import new data to this report?", vbYesNo) = vbNo Then Exit Sub
        
        If MsgBox("Clear the old data first?", vbYesNo) = vbYes Then
            Range("A2:A" & Rows.Count).EntireRow.ClearContents
            NR = 2
        Else
            NR = Range("A" & Rows.Count).End(xlUp).Row + 1
        End If
    
    'Path and filename
        OldDir = CurDir             'memorizes the user's current working path
        fPath = "G:\Excel Tips\Combine Workbooks\WorkbookData\"
        fPathDone = "G:\Excel Tips\Combine Workbooks\WorkbookData\Imported\"   'optional
        ChDir fPath
        fName = Dir("*.xl*")      'filtering key, change to suit
    
    'Import a sheet from found file
        Do While Len(fName) > 0
            'Open file
                Set wbkOld = Workbooks.Open(fName)
            'Find last row and copy data
                Sheets(1).Activate
                LR = Range("A" & Rows.Count).End(xlUp).Row   'find the bottom row of data...change to a different column if "A" isn't reliable for spotting this value
                Range("A2:A" & LR).EntireRow.Copy _
                    wbkNew.Sheets("Master").Range("A" & NR)
            'close file
                wbkOld.Close False
            'Next row
                NR = Range("A" & Rows.Count).End(xlUp).Row + 1
            'move file to "imported" folder
                Name fPath & fName As fPathDone & fName         'optional
            'ready next filename
                fName = Dir
        Loop
    
    'Cleanup
        ActiveSheet.Columns.AutoFit
        Application.DisplayAlerts = True
        Application.EnableEvents = True
        Application.ScreenUpdating = True
    
    'restores user's original working path
        ChDir OldDir
    End Sub

  4. #4
    Registered User
    Join Date
    02-23-2010
    Location
    Ontario, Canada
    MS-Off Ver
    Excel 2003
    Posts
    2

    Re: Combine multiple workbooks into one single workbook

    Try the RDBMerge Add-In at the URL:
    http://www.rondebruin.nl/merge.htm

  5. #5
    Registered User
    Join Date
    12-28-2009
    Location
    USA
    MS-Off Ver
    Excel 2003
    Posts
    98

    Re: Combine multiple workbooks into one single workbook

    so is the code supposed to merge all the data from all the workbooks into one workbook, one master sheet or into one folder? Because it would make more sense to have the files merged into one workbook with the individual sheet being renamed based off of the originating workbook title, wouldn't it??

  6. #6
    Forum Expert JBeaucaire's Avatar
    Join Date
    03-21-2004
    Location
    Bakersfield, CA
    MS-Off Ver
    2010, 2016, Office 365
    Posts
    33,492

    Re: Combine multiple workbooks into one single workbook

    I have a macro for that, too.
    Sub Consolidate()
    'Open all Excel files in a specific folder and import data as separate sheets
    'JBeaucaire (7/6/2009)     (2007 compatible)
    Dim strFileName As String, strPath As String
    Dim wbkOld As Workbook, wbkNew As Workbook, ws As Worksheet
    
    Application.ScreenUpdating = False
    Application.EnableEvents = False
    Application.DisplayAlerts = False
    
    Set wbkNew = ThisWorkbook
    strPath = "G:\Excel Tips\Combine Workbooks\WorkbookData\"
    If Left(strPath, 1) <> "\" Then strPath = strPath & "\"
    
    strFileName = Dir(strPath & "*.xl*")
    wbkNew.Activate
    
    'Clear existing files (optional, remove this section if appending is desired)
    Worksheets.Add(After:=Worksheets(Worksheets.Count)).Name = "Temp"
        For Each ws In Worksheets
            If ws.Name <> "Temp" Then ws.Delete
        Next ws
        
    'Import first active sheet from found file
        Do While Len(strFileName) > 0
            Set wbkOld = Workbooks.Open(strPath & strFileName)
            ActiveSheet.Name = Left(strFileName, Len(strFileName) - 4)
            ActiveSheet.Copy After:=wbkNew.Sheets(wbkNew.Sheets.Count)
            strFileName = Dir
            wbkOld.Close False
        Loop
        
    wbkNew.Sheets("Temp").Delete
    Application.DisplayAlerts = True
    Application.EnableEvents = True
    Application.ScreenUpdating = True
    End Sub

  7. #7
    Valued Forum Contributor
    Join Date
    11-20-2003
    MS-Off Ver
    2010, 2016
    Posts
    1,176

    Re: Combine multiple workbooks into one single workbook

    Still can’t figure out what I am doing incorrectly. I have attached a word document that shows the location of the files I want to combine into one single sheet. Also attached is a copy of the desired output and two example data workbooks.

    I am trying to combine the data in different workbooks in to one single sheet. As an example, say I have 5 workbooks I want to consolidate.
    Book1 – contains data for Apples
    Book2 – contains data for Oranges
    Book3 – contains data for Beans
    Book4 – contains data for Pears
    Book5 – contains data for Bananas

    I need to take all the data from all 5 workbooks and put it into one single workbook. Thank you for your patience on this issue but I don’t know if I have the files in the wrong folders or maybe I am not executing the code correctly. Thanks again.
    Attached Files Attached Files

  8. #8
    Forum Expert JBeaucaire's Avatar
    Join Date
    03-21-2004
    Location
    Bakersfield, CA
    MS-Off Ver
    2010, 2016, Office 365
    Posts
    33,492

    Re: Combine multiple workbooks into one single workbook

    Could be several things. I imagine having the MasterCombined in the same directory as the files to import is probably a bad idea. So move it so that it resides elsewhere, maybe inside the IMPORTED directory?

    Here's one last tweak on the macro, they all work for me, so I can't imagine what's going wrong for you. Your uploaded sheet didn't include the macro, so I couldn't see what/where you actually placed the macro...goes in a standard module (Insert > Module).

    Sub Consolidate()
    'Author:     JBeaucaire'
    'Date:       9/15/2009     (2007 compatible)'
    'Summary:    Open all Excel files in a specific folder and merge data'
    '            into one master sheet (stacked)'
    '            Moves imported files into another folder'
    Dim fName As String, fPath As String, fPathDone As String, OldDir As String
    Dim LR As Long, NR As Long
    Dim wbkOld As Workbook, wbkNew As Workbook, ws As Worksheet
    
    'Setup
        Application.ScreenUpdating = False
        Application.EnableEvents = False
        Application.DisplayAlerts = False
        
        Set wbkNew = ThisWorkbook
        Set ws = wbkNew.Sheets("Start") 'sheet report is built into...edit to match
        
        If MsgBox("Import new data to this report?", vbYesNo) = vbNo Then Exit Sub
        
        If MsgBox("Clear the old data first?", vbYesNo) = vbYes Then
            ws.Range("A2:A" & Rows.Count).EntireRow.ClearContents
            NR = 2
        Else
            NR = ws.Range("A" & Rows.Count).End(xlUp).Row + 1
        End If
    
    'Path and filename
        OldDir = CurDir             'memorizes the user's current working path
        fPath = "G:\Excel Tips\Combine Workbooks\WorkbookData\"
        fPathDone = "G:\Excel Tips\Combine Workbooks\WorkbookData\Imported\"   'optional
        ChDir fPath
        fName = Dir("Book*.xl*")      'filtering key, change to suit
    
    'Import a sheet from found file
        Do While Len(fName) > 0
            'Open file
                Set wbkOld = Workbooks.Open(fName)
            'Find last row and copy data
                Sheets(1).Activate
                LR = Range("A" & Rows.Count).End(xlUp).Row   'find the bottom row of data...change to a different column if "A" isn't reliable for spotting this value
                Range("A2:A" & LR).EntireRow.Copy _
                    ws.Range("A" & NR)
            'close file
                wbkOld.Close False
            'Next row
                NR = Range("A" & Rows.Count).End(xlUp).Row + 1
            'move file to "imported" folder
                Name fPath & fName As fPathDone & fName         'optional
            'ready next filename
                fName = Dir
        Loop
    
    'Cleanup
        ActiveSheet.Columns.AutoFit
        Application.DisplayAlerts = True
        Application.EnableEvents = True
        Application.ScreenUpdating = True
    
    'restores user's original working path
        ChDir OldDir
    End Sub
    Attached Files Attached Files

  9. #9
    Valued Forum Contributor
    Join Date
    11-20-2003
    MS-Off Ver
    2010, 2016
    Posts
    1,176

    Re: Combine multiple workbooks into one single workbook

    PERFECTO!!! Thanks so much. It is exactly what I need. Can't tell you how much time this going to save me.

  10. #10
    Forum Expert JBeaucaire's Avatar
    Join Date
    03-21-2004
    Location
    Bakersfield, CA
    MS-Off Ver
    2010, 2016, Office 365
    Posts
    33,492

    Re: Combine multiple workbooks into one single workbook

    I'm thinking the MasterCombine being in the same folder may explain why it appeared to be working all the way til the end and then suddenly everything disappeared. Hehe, that would be frustrating.

Closed Thread

Thread Information

Users Browsing this Thread

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

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