Search TeachExcel.com
TeachExcel.com
TE
Teach Excel MS Office Tutorials Excel Consulting Services Excel Forum
Excel Video Tutorials Excel Tips Free Excel Macros Excel Help Resources Contact TeachExcel
Video Tutorials
  • Free Macros
  • Excel Help Directory
  • Excel 2007 Resources
  • Keyboard Shortcuts
  • Excel Forum
  • Contact/About

Macros
Excel Tutorials For Macros

Combine Multiple Workbooks into One


Bookmark and Share

This macro for Microsoft Excel allows you to combine multiple workbooks and worksheets into one new workbook and worksheet. When the macro runs, it prompts you to select which excel files from your computer you would like to combine and, once you select them and press ok, this macro will pull data from pre-specified worksheets in the selected workbooks and then combine the data onto one worksheet within a new excel workbook. This works quickly and easily and does not require the hard-coding of file names into the macro.

Note: This macro goes into a Module. Also, you will need to change some cell references and worksheet references if you want the macro to work for your specific needs.

Change the number in this line of code With mybook.Worksheets(1) to choose which worksheet you want data to be copied from in the workbook. 1 means the first sheet and 2 the second sheet etc.

Change the cell references in this line of code Set sourceRange = .Range("A1:A25") to the cells you want to be copied from the old worksheet onto the new worksheet.

Change the column reference in this line of code Set destrange = BaseWks.Range("A" & rnum) which is now "A" to whatever column you would like the cells to be imported.

Change this line of code to point to a specific directory where you want the macro to point by default ChDirNet "C:\".
Where to install the macro:  Module

Excel Macro to Combine Multiple Workbooks into One

Private Declare Function SetCurrentDirectoryA Lib _
    "kernel32" (ByVal lpPathName As String) As Long

Sub ChDirNet(szPath As String)
    SetCurrentDirectoryA szPath
End Sub

Sub Combine_Workbooks_Select_Files()
    Dim MyPath 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
    Dim SaveDriveDir As String
    Dim FName As Variant

    With Application
        CalcMode = .Calculation
        .Calculation = xlCalculationManual
        .ScreenUpdating = False
        .EnableEvents = False
    End With

    SaveDriveDir = CurDir
    ChDirNet "C:\"

    FName = Application.GetOpenFilename(filefilter:="Excel Files (*.xl*), *.xl*", _
                                        MultiSelect:=True)
    If IsArray(FName) Then
        Set BaseWks = Workbooks.Add(xlWBATWorksheet).Worksheets(1)
        rnum = 1
        For Fnum = LBound(FName) To UBound(FName)
            Set mybook = Nothing
            On Error Resume Next
            Set mybook = Workbooks.Open(FName(Fnum))
            On Error GoTo 0
            If Not mybook Is Nothing Then
                On Error Resume Next
                With mybook.Worksheets(1)
                    Set sourceRange = .Range("A1:A25")
                End With
                If Err.Number > 0 Then
                    Err.Clear
                    Set sourceRange = Nothing
                Else
        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 "Not enough rows in the sheet. "
                        BaseWks.Columns.AutoFit
                        mybook.Close savechanges:=False
                        GoTo ExitTheSub
                    Else
                        Set destrange = BaseWks.Range("A" & rnum)
                        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:
    With Application
        .ScreenUpdating = True
        .EnableEvents = True
        .Calculation = CalcMode
    End With
    ChDirNet SaveDriveDir
End Sub


Bookmark and Share


How to Install the Macro
  1. Select and copy the text from within the grey box above.

  2. Open the Microsoft Excel file in which you would like the Macro to function.

  3. Press "Alt + F11" - This will open the Visual Basic Editor - Works for all Excel Versions.  Or For other ways to get there, Click Here.

      For Excel Versions Prior to Excel 2007
      Go to Tools > Macros > Visual Basic Editor

      For Excel 2007
      Go to Office Button > Excel Options > Popular > Click Show Developer tab in the Ribbon. Then go to the Developer tab on the ribbon menu and on the far left Click Visual Basic

  4. On the new window that opens up, go to the left side where the vertical pane is located. Locate your Excel file; it will be called VBAProject (YOUR FILE'S NAME HERE) and click this.

  5. If the Macro goes in a Module, Click Here, otherwise continue to Step 8.

    1. Go to the menu at the top of the window and click Insert > Module
    2. Another window should have opened within the Visual Basic Editor's window. Within this new window, paste the macro code. Make sure to paste the code underneath the last line of anything else that is in the window.
    3. Go to Step 8.

  6. If the Macro goes in the Workbook or ThisWorkbook, Click Here, otherwise continue to Step 8.

    1. Directly underneath your excel file called VBAProject(your file's name here), click the Microsoft Excel Objects folder icon to open that drop-down list.
    2. Then, at the bottom of the list that appears, double-click the ThisWorkbook text.
    3. A new window inside the Visual Basic Editor's window will appear. In this new window, paste the code for the macro. Make sure to paste this code underneath the last line of any other code which is already in the window.
    4. Go to Step 8.

  7. If the Macro goes in the Worksheet Code, Click Here, otherwise continue to Step 8.

    1. Directly underneath your excel file called VBAProject(your file's name here), click the Microsoft Excel Objects folder icon to open that drop-down list.
    2. Within the list that appears you will see every worksheet that is in that excel file. They will be listed as such: Sheet1(NAME OF SHEET HERE) and under that will be Sheet2(NAME OF SHEET HERE). Select the sheet in which you want the macro to run and double-click that sheet.
    3. A new window inside the Visual Basic Editor's window will appear. In this new window, paste the code for the macro. Make sure to paste this code underneath the last line of any other code which is already in the window.
    4. Repeat steps b and c for every sheet you want the macro to work in. Putting the macro in one sheet will not enable it for any other sheets in the workbook.
    5. Go to Step 8.

  8. Close the Microsoft Visual Basic Editor window and save the Excel file. When you close the Visual Basic Editor window, the regular Excel window will not close.

  9. You are now ready to run the macro.



Similar Helpful Excel Resources

Using Vba Scripts To Combine Multiple Workbooks Of Different Number Of Worksheet(s) To A Single Workbook Of Multiple Worksheets - Excel

View Content
Sub Merge2MultiSheets()
Dim wbDst As Workbook
Dim wbSrc As Workbook
Dim wsSrc As Worksheet
Dim MyPath As String
Dim strFilename As String

Application.DisplayAlerts = False
Application.EnableEvents = False
Application.ScreenUpdating = False
MyPath = "C:\MyPath" ' change to suit
Set wbDst = Workbooks.Add(xlWBATWorksheet)
strFilename = Dir(MyPath & "\*.xls", vbNormal)

If Len(strFilename) = 0 Then Exit Sub

Do Until strFilename = ""

Set wbSrc = Workbooks.Open(Filename:=MyPath & "\" & strFilename)

Set wsSrc = wbSrc.Worksheets(1)

wsSrc.Copy After:=wbDst.Worksheets(wbDst.Worksheets.Count)

wbSrc.Close False

strFilename = Dir()

Loop
wbDst.Worksheets(1).Delete

Application.DisplayAlerts = True
Application.EnableEvents = True
Application.ScreenUpdating = True

End Sub


I found this code in a similar (2 year old) post by someone in this forum.
Now I think nobody will post a reply to my question in that thread, so I am starting a new one.
I am looking for a code which will move all the sheets in the directory to one single workbook and the source workbook should remain intact.
(Instead of this code I need a code which will copy all the workbooks not just one, and the code should not delete the source file or any of its contents)
I am below Zero when it comes to VBA, so please help me out.

Combine Multiple Workbooks Into One - Excel

View Content
So far my code will allow me to select text files and convert them into excel workbooks, one text file = one workbook. There may be times when 20 text files are selected and other times 10. The part I'm stuck with is taking all of the workbooks and combining all of the information into one workbook calling it "Master" and then deleting the workbooks not needed. Any help would be appreciated. Thanks in advance! Here is the code so far:
Code:

Application.ScreenUpdating = False
' File filters
Filter = "Excel Files (*.xls),*.xls," & _
        "Text Files (*.txt),*.txt," & _
        "All Files (*.*),*.*"
'   Default filter to *.*
    FilterIndex = 3
' Set Dialog Caption
Title = "Select File(s) to Open"
' Select Start Drive & Path
ChDrive ("J")
ChDir ("J:\dell\use\reports\test")
With Application
    ' Set File Name Array to selected Files (allow multiple)
    FileName = .GetOpenFilename(Filter, FilterIndex, Title, , True)
    ' Reset Start Drive/Path
    ChDrive (Left(.DefaultFilePath, 1))
    ChDir (.DefaultFilePath)
End With
' Exit on Cancel
If Not IsArray(FileName) Then
    MsgBox "No file was selected."
    Exit Sub
End If
' Open Files
For i = LBound(FileName) To UBound(FileName)
    'msg = msg & Filename(i) & vbCrLf ' This can be removed
    Workbooks.Open FileName(i)
    Set wsThis = ActiveSheet
    Set myRange = wsThis.Range("A1:A5000")
    numR = myRange.count
        For r = 1 To numR + 1
            If (wsThis.Cells(r, 2))  "Error" Then
                    Rows(r).Select
                    Selection.Delete Shift:=xlUp
                    r = r - 1
            End If
            If (wsThis.Cells(r + 1, 2)) = "" Then
                    Exit For
          End If
        Next r
        Cells.Select
        Cells.EntireColumn.AutoFit
        Range("A1").Select
        If Cells(1, 1) = "" Then
            ActiveWindow.Close False
        End If
Next i
Application.ScreenUpdating = True
End Sub




Combine Multiple Workbooks - Excel

View Content
Hi all - I have a weekly task to combine 16 spreadsheets sent to me into one document.
Each workbook is identical containing the same format just different figures (weekly report)
Is there a quick way to combine these spreadsheets, so that rather than 16 .xls files they are one file with 16 tabs?
The current method of copy and paste works fine - but would be great if there is a process to speed this rather mundane weekly task!

Combine Multiple Workbooks - Excel

View Content
Basically, what i'm trying to do is combine multiple workbooks with multiple tabs into one raw data sheet that can be used for a pivot table. this raw data sheet should live in its own workbook and be updated with new data from the pre-selected reference workbooks whenever the macro is run.

So, i am currently using 2 codes, one that pulls workbooks i select and dump them into my raw data workbook, and one that takes all the tabs in my raw data workbook and dumps them into my raw data tab. couple of problems with the first macro, one, it's restricted to macro-enabled workbooks (which i don't mind, but i'd rather it pulled any excel file) and two, it will duplicate a file i've already add to the workbook rather than updating the existing tabs for said file. the second macro runs fine, and i can live with this whole process as long as i can get help fixing the below macro to accept all types of excel files and not duplicate files i've already added to the raw data workbook, and instead update said tabs with the new info.

Any help is appreciated, here's the code:

Code:

Sub CombineWorkbooks()
    Dim FilesToOpen
    Dim x As Integer

    On Error GoTo ErrHandler
    Application.ScreenUpdating = False

    FilesToOpen = Application.GetOpenFilename _
      (FileFilter:="Microsoft Excel Files (*.xlsm), *.xlsm", _
      MultiSelect:=True, Title:="Files to Merge")

    If TypeName(FilesToOpen) = "Boolean" Then
        MsgBox "No Files were selected"
        GoTo ExitHandler
    End If

    x = 1
    While x <= UBound(FilesToOpen)
        Workbooks.Open Filename:=FilesToOpen(x)
        Sheets().Move After:=ThisWorkbook.Sheets _
          (ThisWorkbook.Sheets.Count)
        x = x + 1
    Wend

ExitHandler:
    Application.ScreenUpdating = True
    Exit Sub

ErrHandler:
    MsgBox Err.Description
    Resume ExitHandler
End Sub




Combine Multiple Ranges From Different Workbooks - Excel

View Content
I found the following code that merges one range from all workbooks in a folder into one new worksheet. As of now, the code is copying the range ("B4:L4") on the third tab of every workbook. Is there a way to modify this code to also copy the ranges ("P4:R4") and ("V4:AA4")? Essential I want to be able to copy multiple ranges instead of just one.

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.
    MyPath = "Z:\My Documents\Analyst Recommendations\Top Analysts\Analysts Results\JP Morgan\Test"

    ' 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.
    Set BaseWks = Workbooks.Add(xlWBATWorksheet).Worksheets(1)
    rnum = 1

    ' 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.
                With mybook.Worksheets(3)
                    Set sourceRange = .Range("B4:L4")
                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




Combine (not Total) Multiple Workbooks - Excel

View Content
Hello,
I couldn't find a previous thread on this specifically. I am trying to take multiple workbooks (2nd sheet in each workbook to be exact) and copy/paste every line of data from each into a master. Column headings in each wkbk are identical. I don't think Consolidate will work unless I use a count/offset function in a named range. Any ideas on code would be much appreciated.

Combine Worksheets From Multiple Workbooks - Excel

View Content
I just want all the worksheets from multiple workbooks from one folder in one workbook with the worksheet names changed so it includes the file name (especially since there will lots of duplication). I actually want all the data together but because formatting is confused with lots of variance including numbers of worksheets merely getting it in one workbook would be a fantastic start. Thanks in advance. I don't mind if there is a suitable thread to refer to.

Combine 2 Workbooks Together With Multiple Worksheets - Excel

View Content
Hi all,

I have been searching for ever now and can't seem to find what I am looking for...(maybe I am wording it wrong)

What I have to do is take Workbook 1 and copy all the data and paste it under all the data in Workbook 2... and do this for about 200 worksheets per workbook, all of them with the same titles.

So for example....

Take all of the rows with data in them starting with row 4, from Workbook 1, Worksheet 1 and paste them under all the rows with data in Workbook 2, Worksheet 1.

Then.... go to Worksheet 2, then Worksheet 3 and so on...

I program in Java, and know a little about VBA, but not nearly enough to get this hammered out... Any help would be greatly appreciated.

Thanks

Combine Multiple Workbooks Macro? - Excel

View Content
I'm using Excel 2000 on Windows XP at work and I am trying to find a macro that can combine a bunch of different workbooks all on one worksheet.

I'm working with hundreds of exported workbooks which all have one worksheet and several hundred rows of data. Basically I want to append all the data from each workbook into a giant master file.

I was able to google from macros but none of them worked correctly.

Any help is appreciated thanks.

Combine Specific Data From Multiple Workbooks - Excel

View Content
Hi all,

I'm trying to pull information from several different workbooks (which are invoices) into a single worksheet. I may have 40 different identical workbooks. and I'm trying to pull specific data from each of them and list them (stack) in the single worksheet.

For instance, if E13 on each of the 40 workbooks is a person's name, I'd like to drop each of those values into the combined worksheet, starting at C2 and going from there (C3, C4, etc).

Can someone point me in the right direction?

Thanks!
David

Random Tutorials
Bond Pricing Calculations for Simple Bonds
         - Future Value, Present Value, Interest Rate, etc.

(Intermediate)
Remove #N/A Error Result from Empty VLOOKUP() Formulas
(Intermediate)
AND(), OR(), and IF() Statements/Formulas
(Intermediate)
Absolute and Relative Cell References
   - & INDIRECT() Function Introduction

(Easy)
Consolidate & Combine Data from Separate Worksheets or Workbooks(Excel Files)
(Intermediate)
How to record a Macro - And what One is
(Easy)
Submit Inquiry Here
  • Prices From $10
Name:*
E-mail:*
Request:*
The macro(s) on this page will be sent with the request.
Contact | Privacy Policy | Disclaimer
Copyright© 2012 TeachExcel.com