How to merge excel files in one file

You have several Excel workbooks and you want to merge them into one file? This could be a troublesome and long process. But there are 6 different methods of how to merge existing workbooks and worksheets into one file. Depending on the size and number of workbooks, at least one of these methods should be helpful for you. Let’s take a look at them.

Summary

If you want to merge just a small amount of files, go with methods 1 or method 2 below. For anything else, please take a look at the methods 4 to 6: Either use a VBA macro, conveniently use an Excel-add-in or use PowerQuery (PowerQuery only possible if the sheets to merge have exactly the same structure).

Method 1: Copy the cell ranges

copy, paste, source, main, merge, join
Copy and paste the source content into your main workbook.

The obvious method: Select the source cell range, copy and paste them into your main workbook. The disadvantage: This method is very troublesome if you have to deal with several worksheets or cell ranges. On the other hand: For just a few ranges it’s probably the fastest way.

Method 2: Manually copy worksheets

copy, move, worksheet, sheet, excel
Copy worksheets separately to the “master” workbook.

The next method is to copy or move one or several Excel sheets manually to another file. Therefore, open both Excel workbooks: The file containing the worksheets which you want to merge (the source workbook) and the new one, which should comprise all the worksheets from the separate files.

  1. Select the worksheets in your source workbooks which you want to copy. If there are several sheets within one file, hold the Ctrl key computer_key_Ctrland click on each sheet tab. Alternatively, go to the first worksheet you want to copy, hold the Shift key computer_key_Shift and click on the last worksheet. That way, all worksheets in between will be selected as well.
  2. Once all worksheets are selected, right click on any of the selected worksheets.
  3. Click on “Move or Copy”.
  4. Select the target workbook.
  5. Set the tick at “Create a copy”. That way, the original worksheets remain in the original workbook and a copy will be created.
  6. Confirm with OK.

One small tip at this point: You can just drag and drop worksheets from one to another Excel file. Even better: If you press and hold the Ctrl-Key when you drag and drop the worksheets, you create copies.


Do you want to boost your productivity in Excel?

Get the Professor Excel ribbon!

Add more than 120 great features to Excel!


Method 3: Use the INDIRECT formula

The next method comes with some disadvantages and is a little bit more complicated. It works, if your files are in a systematic file order and just want to import some certain values. You build your file and cell reference with the INDIRECT formula. That way, the original files remain and the INDIRECT formula only looks up the values within these files. If you delete the files, you’ll receive #REF! errors.

indirect, link, other, file, excel
With the INDIRECT formula you can link to other files. Only condition: the source file must be open in the background.

Let’s take a closer look at how to build the formula. The INDIRECT formula has only one argument: The link to another cell which can also be located within another workbook.

  1. Copy the first source cell.
  2. Paste it into your main file using paste special (Ctrl computer_key_Ctrl+ Alt computer_key_Alt+ v computer_key_V). Instead of pasting it normally, click on “Link” in the bottom left corner of the Paste Special window. That way, you extract the complete path. In our case, we have the following link:
    =[160615_Examples.xlsm]Thousands!$C$4
  3. Now we wrap the INDIRECT formula around this path. Furthermore, we separate it into file name, sheet name and cell reference. That way, we can later on just change one of these references, for instance for different versions of the same file. The complete formula looks like this (please also see the image above):
    =INDIRECT(“‘”&$A3&$B3&”‘!”&D$2&$C3)

Important – please note: This function only works if the source workbooks are open.

Method 4: Merge files with a simple VBA macro

You are not afraid of using a simple VBA macro? Then let’s insert a new VBA module:

  1. Go to the Developer ribbon. If you can’t see the Developer ribbon, right click on any ribbon and then click on “Customize the Ribbon…”. On the right hand side, set the tick at “Developer”.
  2. Click on Visual Basic on the left side of the Developer ribbon.
  3. Right click on your workbook name and click on Insert –> Module.
  4. Copy and paste the following code into the new VBA module. Position the cursor within the code and click start (the green triangle) on the top. That’s it!
Sub mergeFiles()
    'Merges all files in a folder to a main file.
    
    'Define variables:
    Dim numberOfFilesChosen, i As Integer
    Dim tempFileDialog As fileDialog
    Dim mainWorkbook, sourceWorkbook As Workbook
    Dim tempWorkSheet As Worksheet
    
    Set mainWorkbook = Application.ActiveWorkbook
    Set tempFileDialog = Application.fileDialog(msoFileDialogFilePicker)
    
    'Allow the user to select multiple workbooks
    tempFileDialog.AllowMultiSelect = True
    
    numberOfFilesChosen = tempFileDialog.Show
    
    'Loop through all selected workbooks
    For i = 1 To tempFileDialog.SelectedItems.Count
        
        'Open each workbook
        Workbooks.Open tempFileDialog.SelectedItems(i)
        
        Set sourceWorkbook = ActiveWorkbook
        
        'Copy each worksheet to the end of the main workbook
        For Each tempWorkSheet In sourceWorkbook.Worksheets
            tempWorkSheet.Copy after:=mainWorkbook.Sheets(mainWorkbook.Worksheets.Count)
        Next tempWorkSheet
        
        'Close the source workbook
        sourceWorkbook.Close
    Next i
    
End Sub

Method 5: Automatically merge workbooks

The fifth way is probably most convenient:

Click on “Merge Files” on the Professor Excel ribbon.

Now select all the files and worksheets you want to merge and start with “OK”.

This procedure works well also for many files at the same time and is self-explanatory. Even better: Besides XLSX files, you can also combine XLS, XLSB, XLSM, CSV, TXT and ODS files.

To do that you need a third party add-in, for example our popular “Professor Excel Tools” (click here to start the download).

Here is the whole process in detail:

Just click on "Merge Files" on the Professor Excel ribbon, select your files and click on OK.

Just click on “Merge Files” on the Professor Excel ribbon, select your files and click on OK.

Method 6: Use the Get & Transform tools (PowerQuery)

merge, workbooks, get, transform, complete, folder
merge, workbooks, get, transform, complete, folder
merge, workbooks, get, transform, complete, folder

The current version of Excel 365 offers the “Get & Transform” tools to import data. These functions are very powerful and are supposed to replace the old “Text Import Wizard”. However, they have one useful feature: Import a complete folder of documents.

The requirements: The workbooks and worksheets you want to import have to be in the same format.

Please follow these steps for importing a complete folder of Excel files.

  1. Create a folder with all the documents you want to import.
  2. Usually it’s the fastest to just copy the folder path directly from the Windows Explorer. You still have the change to later-on select the folder, though.
  3. Within Excel, go to the Data ribbon and click on “Get Data”, “From File” and then on “From Folder”.
  4. Paste the previously copied path or select it via the “Browse” function. Continue with “OK”.
  5. If all files are shown in the following window, either click on “Combine” (and then on “Combine & Load To”) or on “Edit”. If you click on “Edit”, you can still filter the list and only import a selection of the files in the list. Recommendation: Put only the necessary files into your import folder from the beginning so that you don’t have to navigate through the complex “Edit” process.
  6. Next, Excel shows an example of the data based on the first file. If everything seems fine, click on OK. If your files have several sheets, just select the one you want to import, in this example “Sheet1”. Click on “OK”.
  7. That’s it, Excel now imports the data and inserts a new column containing the file name.

For more information about the Get & Transform tools please refer to this article.

Next step: Merge multiple worksheets to one combined sheet

After you have combined many Excel workbooks into one file, usually the next step is this: Merge all the imported sheets into one worksheet.

Because this is a whole different topic by itself, please refer to this article.

Image by MartinHolzer from Pixabay

You have several Excel files that make it harder for you to access data. You keep switching between different opened files, and this process takes a lot of your time. You are well aware that it is a lot easier to process data in a single file instead of switching between numerous sources. Then comes the question, how can I merge all these files into one comprehensive file? It is a troublesome and long process trying to combine different Excel files into one file when you factor in the number of worksheets found in one workbook. There are various ways of merging Excel files.

In this article, we discuss how to merge multiple Excel files into one file. Let’s get started.

Method 1: Combine multiple workbooks into one workbook with the Move or Copy function

1. If you want to merge all the existing files into a new Excel workbook, create the new Excel workbook and open it. But if you’re going to combine all of them into a current workbook, open that workbook.

2. Open all the Excel files you want to merge. You need to open all files to be able to combine them into one. Instead of doing it manually, select all the files and press the enter key on your keyboard. To select multiple files that are non-adjacent, hold the Ctrl key and click the files one by one. For adjacent files, hold the Shift key and click on the last file to select them all.

3. Maximize the first file you want to merge.

4. Right-click the worksheet you want to merge, then select Move or Copy.

5. On the pop-up window, click ‘Pick from Drop-down List.’ All the Excel files opened on your computer will be displayed here

6. Select the excel file you want to merge other files into in the ‘To book’ drop-down arrow.

7. To merge excel files, check the Create a copy checkbox.

8. In the Before Sheet section, select ‘move to end and click OK. It will create a copy of the worksheet in the destination file.

9. Repeat all the above steps for all the remaining files and save your file.

Method 2: Combine multiple workbooks into one with VBA

1. Open a new workbook that will act as a master workbook.

2. Press Alt + F11 to the VBA page

3. Click on the Insert tab. Next, select the Module tab.

4. Copy and paste the macro code below.

Sub GetSheets()

Path = "C:UsersdtDesktopdt kte"

Filename = Dir(Path & "*.xlsx")

  Do While Filename <> ""

  Workbooks.Open Filename:=Path & Filename, ReadOnly:=True

     For Each Sheet In ActiveWorkbook.Sheets

     Sheet.Copy After:=ThisWorkbook.Sheets(1)

  Next Sheet

     Workbooks(Filename).Close

     Filename = Dir()

  Loop

End Sub

Click here for more code.

5. After this, it is time to initiate the command by pressing F5 to run the excel macro code. Doing this will open a file and then copy the data. It will paste the same in your new workbook. Close the workbook.

Method 3: Merging Microsoft Excel files as CSV files.

1. Open the excel files.

2. Go to the Menu bar. Click File. Then Save As.

4. In the Save as type, there is a drop-down list. Select CSV from the list.

5. Do this for all the files you want to merge, and then place all the CSV files into one folder.

6. Open the command prompt then navigate to your folder. Type the following command to merge all CSV files in the folder into a new CSV file. Copy *.csv newfile.CSV

7. After creating the new file, open the new CSV file in Microsoft Excel.

8. Save it as an Excel file.

Method 4: Using Power Query

The Power Query method is the best way to merge data since you only need to store all the excel files in a single folder. You can then use that folder to load data from files into the Power Query Editor. It also allows you to transform data while combining.

However, for the Power Query editor to merge Excel files, you need to understand that all data should be structured in the same way. That means the number of columns and their order should be the same. Below are steps to follow when merging files with the Power Query application.

Power query allows to import, edit and consolidate the data. It can also be used to import and combine multiple excel files into one folder.

With the Same Name of Worksheets and Tables

1. Move all the files into the new folder that you want to combine.

2. In Excel go to the Data tab

3. Press Get Dat > From File > From Folder

4. Browse and select the folder path

5. Press Ok

6. If files are ready to combine press Combine & Load

7. If you want to manipulate the data, then press the Transform Data button. This will open the query editor where you can work on the data.

From here, select the table in which you have data in all the workbooks. A preview of this will appear at the side of the window.

8. Once you select the table, click OK to merge data from all the files into your Power Query editor. You will see a new column with the name of the workbooks from which data is extracted.

9. Right-click on the column header and select “Replace Values”.

10. Enter the text “.xlsx” in the Replace Values box and leave the “Replace With” box blank. The idea here is to remove the file extension from the name of the workbook.

11. Next, double-click on the header and select “Rename” to enter a name for the column.

12. At this point, your merged data is ready and you only need to load it into your new workbook. To perform this, go to the Home Tab and click on Close & Load. Now you will have your combined data from all tables or workbooks with the same name in a single workbook.

Note: You will not have the same table name in all the excel files all the time. At that point, you can use the worksheet name to combine data with the Power Query method. However, you should note two points when using the worksheet name to combine data with the power query method:

  • Power Query is case-sensitive. So, you should have the same letter names of worksheets in all the workbooks.
  • You should have the same name for the column headers, but the order of the columns does not matter. If column1 in the north.xlxs is column2 in the west.xlxs, Power Query will match it, but you need to have the same column names.

Therefore, when combining files using the power query, you can use the worksheet name instead of the table name. You only need to select the worksheet name, click on the Combine & Edit, and follow all the steps outlined above from step number 6.

When You Don’t Have the Same Name of Worksheets and Tables.

In some situations, you can lack the same name of worksheets and tables in the excel files. In this case, you must know how to combine data from these different worksheets and tables into one file, following these steps:

1. Open the “From Folder” dialog box to locate the folder where you have all the files and click OK.

2. After that, click on the “Edit” to edit the table.

3. Once the table and Power Query editor open, select the first two columns of the table and click on the Remove other Columns from the right-click menu.

4. From here, you need to add a custom column to fetch data from the worksheets of the workbooks. To do this, go to Add Column Tab and click on the Custom Column button. The step will automatically open the Custom Column in the dialog box.

5. In the dialog box enter the formula below and click OK.

                 =Excel.Workbook([Content])

6. You will have a new column in the table from which you need to extract data. Open the filter from that newly added custom column and click OK to expand all the data into the table.

7. You will see a newly expanded table with some new columns. Delete all columns from the new table except the third and the fourth column.

8. Now open the filter for the Custom Data column to expand it and click OK.

Once you click OK, you will get all the data from the files having been merged into a single table. Though, if you notice all the headings of the columns are in the data itself, you need to add the column headings as follows;

  • Double-click on the header and add a name. You can also right-click and select Rename It.
  • Exclude the headings you have in the data table. For this, open any column’s filter options and unselect the heading name which you have in the column data and click OK after that. After you click ok, your data is ready to load into the worksheet.
  • Go to the Home Tab and click on Close and Load. This allows you to combine data from different workbooks that had different worksheets names.

At this point, you have already merged the data into one single file. You should then apply some formatting to avoid losing a single file of your data when updating it. To format a single file, you can use these steps:

  • Go to Design Tab and open Properties.
  • Untick the Adjust Column width and tick the Preserve Cell Formatting

Conclusion

The above tips help you to be organized and save time. Whether you decide to merge data in excel into a single file, or if you prefer to spread your work across multiple files, either of the methods above will help you. Excel offers immense features such as an in-built tracking feature that keeps track of any changes made in your files. So, losing your original data should not be a cause of dilemma.

Which option would you choose: have three Excel files with one worksheet each or one Excel file with three worksheets? The former is not practical and convenient from the user’s perspective. Whereas, the latter allows you to easily navigate and manipulate your records in one place. So, let’s organize your data in an efficient way by merging Excel files into one. This tutorial will help you combine multiple Excel files into one according to your needs.

How to merge Excel files – all options introduced

Most of us love Excel for its functional diversity. This means that you can do a certain action or task in multiple ways depending on your needs. For example, you can merge Excel files in the following ways:

  • Manually copy data from multiple workbooks, then paste it into one worksheet.
  • Manually copy worksheets from multiple files to a single workbook.
  • Link or export data from multiple worksheets in a single workbook.
  • Merge multiple Excel files using Power Query.
  • Merge Excel files into a single workbook using VBA macros.

If you already know which case is yours, jump right into the required section. However, we advise you read the entire guide to learn the details of merging Excel files.

How to merge two Excel files the easy way

Here we have two Excel files with one worksheet each. 

1.1 two excel files

The simplest way to merge two Excel files is to copy a data range from one of them and paste it into another one:

  • On one of the files, select a data range, then right-click and select Copy.

1.2 copy dataset excel

  • Go to the other file, select a cell where you want to paste the data, then right-click and select Paste.

1.3 paste dataset excel

In our case, we forgot to exclude the first row with column names when we copied the data range and got the following result:

1.4 merge two excel files manually

So if you use this method to merge Excel files, make sure to select the proper data range.

Obviously, this method is plain enough. However, it won’t be suitable if your Excel files contain hundreds or thousands of rows you want to merge. Let’s proceed to other options then.

How to combine multiple Excel files into one by copying their sheets

We have three Excel files with one worksheet each. We want to combine multiple excel files into one workbook but keep these separate sheets in one Excel file. So, we just need to copy these sheets.

  • Open all the files.

2.1 open three excel files

  • Right-click on the sheet you want to copy and select Move or Copy…
2.2 move or copy excel sheet
  • Select the file where you want to copy your sheet to, and check the Create a copy checkbox.
2.3 move or copy excel sheet
  • Repeat this process for the rest of the sheets, and there you go:
2.4 sheets copied to one excel file

Now you have all the sheets from separate Excel files merged in one Excel workbook.

Merge Excel files online

If you work in Excel Online and you need to merge your files located in cloud storage such as OneDrive, you can:

  • Manually copy and paste data.
  • Link Excel sheets using Workbook links.
  • Import Excel sheets from your files to a single Excel workbook and even automate the import on a schedule.

The latter option seems to be the most actionable one, so let’s dive in.

Merge multiple Excel files into one sheet

We have three Excel files on OneDrive with one worksheet each. 

3.1 merge excel files online

Let’s merge the data from these files into one sheet in the workbook Excel-File-1. The Excel integration by Coupler.io will do the job with just a few clicks.

Coupler.io is a data integration tool that allows you to schedule imports from multiple sources, such as Excel, CSV, Airtable, and many others to Microsoft Excel, Google Sheets, or Google BigQuery.

Sign up to Coupler.io with your Microsoft account, click Add importer, then select Microsoft Excel both as a source and destination app. Check out other Excel integrations.

3.2 merge excel files online

Then proceed with the setup.

Source

  • Connect your Microsoft account.
  • Select an Excel file on OneDrive and a sheet to take data from. You can select multiple sheets from a single file, but the data extracted from them will be merged into one sheet.

3.3 merge excel files online source

Destination

  • Connect your Microsoft account.
  • Select an Excel file on OneDrive and a sheet where to load the data. 

3.4 merge excel files online destination

  • Select the Append import mode to have your imported data merged not replaced.

3.5 merge excel files online append mode

You can now click Save and Run to load the data. Here is the result:

3.6 merge excel files online merge point

However, this merged data is from only two files, while we have three. You need to set up another integration for the third file. You can make a copy of this integration to speed up the setup. Click the three dots on the top-right and select Copy.

3.7 merge excel files online copy

Then replace the source file and keep the destination settings unchanged.

3.8 merge excel files online copy importer

Note: Double-check the Sheet in the Destination settings since it may be suggested that you make a copy of it. 

Now you can click Save and Run to add the data from the third Excel file to the already merged rows from two Excel files.

How to automatically merge Excel files

Coupler.io allows you to schedule imports of data from the Excel files you want to merge. So, you can combine multiple Excel files into one automatically.

For this, you need to enable the Automatic data refresh feature and configure the desired schedule. You can do this either when setting up your importer:

12.Coupler.io schedule

Or do this at any time later in the admin panel:

3.9 automatically merge excel files online

Merge Excel files with Power Query

Excel Power Query is a built-in data transformation engine that allows you to perform basic and advanced transformations with your data. Let’s see how it can cope with merging Excel files.

How to merge 3 Excel files into one

Again, we have three Excel files with one worksheet each. Locate all the files in one folder. 

  • Open a new Excel workbook. Go to New Query=> From File => From Folder

4.1 merge excel files power query new query

  • Browse and select the folder with your Excel files.

4.2 merge excel files power query path

  • On the next step, you’ll have three options:
    • Combine and Transform Data – choose this if you want to manipulate the data before merging it.
    • Combine and Load – choose this if you want to merge Excel files right away.
    • Combine and Load To… – choose this if you want to merge Excel files into another workbook.

4.3 merge excel files power query combine and load

  • On the next step, you can optionally select the object to extract from each file. Click OK.

4.4 merge excel files power query select object

  • Eventually, your files are merged into one.

4.5 merge excel files power query results

Merge 2 Excel files based on a column

Let’s solve a more complex task of merging Excel files using Power Query. We have two Excel files with one worksheet each, and we need to merge them based on a key column. In our example, let’s merge the rows that have matches based on the first_name value, if any. Here is the flow:

  • Open a new Excel workbook. Go to New Query => From File => From Workbook.

5.1 merge excel files power query new query workbook

  • Select a file and a sheet, then click Load. The data will be loaded in the form of a table.

5.2 merge excel files power query table

  • Repeat these steps to load data from the second file. As a result, you’ll have two queries.

5.3 merge excel files power query two queries

  • Go to the Query tab, then select Merge.

5.4 merge excel files power query

  • Select tables and matching columns to merge data. Once you do this, you’ll see the number of rows that match based on the selected key column. Click OK to proceed.

5.5 merge excel files power query select tables and columns

  • Then you’ll see a preview of the merged queries in the Power Query Editor.

5.6 merge excel files power query preview

If you’re not going to make any additional manipulations, click Close & Load. Here is the result.

5.7 merge excel files power query merged queries

How to merge two Excel files and remove duplicates

To remove duplicates during the process of merging Excel files, you’ll need to repeat the flow we described in the previous section. And on the step of a preview of the merged queries in the Power Query Editor, go to Home => Remove Rows => Remove Duplicates.

5.8 remove duplicates

And that’s it 🙂

How to combine multiple Excel files into one workbook and compare them

The flow that we described in the section about merging two Excel files based on a column will let you merge and compare files. You’ll need to choose a key column to compare the data from both files, and then you’ll see whether there are any matches. 

Combine data from multiple Excel files into one pivot table

Let’s add another condition to our task – combine multiple Excel workbooks into one pivot table. The Power Query will let you do this easily. For this, you’ll need first to consolidate your files as we described above. Once you have the data consolidated in one table/sheet, click the Summarize with PivotTable button in the Design menu.

pivot table

After that, you can configure the pivot table to your needs.

pivot table 2

How to combine multiple Excel files into one worksheet using macro

Excel macros are pieces of code that can implement specific actions including merging Excel files. In our guide on Excel macros, you can learn more about using and creating macros. 

And here, we’d like to introduce a few ready-to-use VBA macros to optimize the consolidation of data from multiple Excel files.

  • Go to the Developer tab => Visual Basic

6.1 excel vba macro merge excel files

  • Go to Insert => Module
6.2 excel vba macro merge excel files insert module
  • In the open window, enter one of the following scripts and run it.

6.3 excel vba macro merge excel files run module

Excel VBA macro to combine multiple Excel files into one workbook

This macro will combine all open Excel files into one new workbook.

Sub MergeFilesNewWorkbook()
On Error GoTo eh
'declare variables to hold the objects required
 Dim wbDestination As Workbook
 Dim wbSource As Workbook
 Dim wsDestination As Worksheet
 Dim wb As Workbook
 Dim sh As Worksheet
 Dim strSheetName As String
 Dim strDestName As String
 Dim iRws As Integer
 Dim iCols As Integer
 Dim totRws As Integer
 Dim strEndRng As String
 Dim rngSource As Range
'turn off the screen updating to speed things up
 Application.ScreenUpdating = False
'first create new destination workbook
 Set wbDestination = Workbooks.Add
'get the name of the new workbook so you exclude it from the loop below
 strDestName = wbDestination.Name
'now loop through each of the workbooks open to get the data
 For Each wb In Application.Workbooks
 If wb.Name <> strDestName And wb.Name <> "PERSONAL.XLSB" Then
 Set wbSource = wb
 For Each sh In wbSource.Worksheets
'get the number of rows and columns in the sheet
 sh.Activate
 ActiveSheet.Cells.SpecialCells(xlCellTypeLastCell).Activate
 iRws = ActiveCell.Row
 iCols = ActiveCell.Column
'set the range of the last cell in the sheet
 strEndRng = sh.Cells(iRws, iCols).Address
'set the source range to copy
 Set rngSource = sh.Range("A1:" & strEndRng)
'find the last row in the destination sheet
 wbDestination.Activate
 Set wsDestination = ActiveSheet
 wsDestination.Cells.SpecialCells(xlCellTypeLastCell).Select
 totRws = ActiveCell.Row
'check if there are enough rows to paste the data
 If totRws + rngSource.Rows.Count > wsDestination.Rows.Count Then
 MsgBox "There are not enough rows to place the data in the Consolidation worksheet."
 GoTo eh
 End If
'add a row to paste on the next row down
 If totRws <> 1 Then totRws = totRws + 1
 rngSource.Copy Destination:=wsDestination.Range("A" & totRws)
 Next sh
 End If
 Next wb

'clean up the objects to release the memory
 Set wbDestination = Nothing
 Set wbSource = Nothing
 Set wsDestination = Nothing
 Set rngSource = Nothing
 Set wb = Nothing
'turn on the screen updating when complete
 Application.ScreenUpdating = False
Exit Sub
eh:
MsgBox Err.Description
End Sub

Excel VBA macro to merge all open Excel files into an existing workbook

This macro will combine all open Excel files into one existing workbook.

Sub MergeFilesExistingWorkbook()
 On Error GoTo eh
'declare variables to hold the objects required
 Dim wbDestination As Workbook
 Dim wbSource As Workbook
 Dim wsDestination As Worksheet
 Dim wb As Workbook
 Dim sh As Worksheet
 Dim strSheetName As String
 Dim strDestName As String
 Dim iRws As Integer
 Dim iCols As Integer
 Dim totRws As Integer
 Dim rngEnd As String
 Dim rngSource As Range
'set the active workbook object for the destination book
 Set wbDestination = ActiveWorkbook
'get the name of the active file
 strDestName = wbDestination.Name
'turn off the screen updating to speed things up
 Application.ScreenUpdating = False
'first create new destination worksheet in your Active workbook
 Application.DisplayAlerts = False
'resume next error in case sheet doesn't exist
 On Error Resume Next
 ActiveWorkbook.Sheets("Consolidation").Delete
'reset error trap to go to the error trap at the end
 On Error GoTo eh
 Application.DisplayAlerts = True
'add a new sheet to the workbook
 With ActiveWorkbook
 Set wsDestination = .Sheets.Add(After:=.Sheets(.Sheets.Count))
 wsDestination.Name = "Consolidation"
 End With
'now loop through each of the workbooks open to get the data
 For Each wb In Application.Workbooks
 If wb.Name <> strDestName And wb.Name <> "PERSONAL.XLSB" Then
 Set wbSource = wb
 For Each sh In wbSource.Worksheets
'get the number of rows in the sheet
 sh.Activate
 ActiveSheet.Cells.SpecialCells(xlCellTypeLastCell).Activate
 iRws = ActiveCell.Row
 iCols = ActiveCell.Column
 rngEnd = sh.Cells(iRws, iCols).Address
 Set rngSource = sh.Range("A1:" & rngEnd)
'find the last row in the destination sheet
 wbDestination.Activate
 Set wsDestination = ActiveSheet
 wsDestination.Cells.SpecialCells(xlCellTypeLastCell).Select
 totRws = ActiveCell.Row
'check if there are enough rows to paste the data
 If totRws + rngSource.Rows.Count > wsDestination.Rows.Count Then
 MsgBox "There are not enough rows to place the data in the Consolidation worksheet."
 GoTo eh
 End If
'add a row to paste on the next row down if you are not in row 1
 If totRws <> 1 Then totRws = totRws + 1
 rngSource.Copy Destination:=wsDestination.Range("A" & totRws)
 Next sh
 End If
 Next wb
 
'clean up the objects to release the memory
 Set wbDestination = Nothing
 Set wbSource = Nothing
 Set wsDestination = Nothing
 Set rngSource = Nothing
 Set wb = Nothing
'turn on the screen updating when complete
 Application.ScreenUpdating = False
Exit Sub
eh:
MsgBox Err.Description
End Sub

Excel VBA macro to combine multiple Excel files into one workbook as separate sheets

This macro will combine all open Excel files into one new workbook and keep them as separate sheets.

Sub MergeFilesSeparateSheets()
On Error GoTo eh
    'declare variables to hold the objects required
Dim wbDestination As Workbook
Dim wbSource As Workbook
Dim wsSource As Worksheet
Dim wb As Workbook
Dim sh As Worksheet
Dim strSheetName As String
Dim strDestName As String
    'turn off the screen updating to speed things up
Application.ScreenUpdating = False 'first create new destination workbook
Set wbDestination = Workbooks.Add 'get the name of the new workbook so you exclude it from the loop below
strDestName = wbDestination.Name 'now loop through each of the workbooks open to get the data but exclude your new book or the Personal macro workbook
For Each wb In Application.Workbooks
If wb.Name <> strDestName And wb.Name <> "PERSONAL.XLSB" Then
Set wbSource = wb
For Each sh In wbSource.Worksheets
sh.Copy After:=Workbooks(strDestName).Sheets(1)
Next sh
End If
Next wb

Application.DisplayAlerts = True 'clean up the objects to release the memory
Set wbDestination = Nothing
Set wbSource = Nothing
Set wsSource = Nothing
Set wb = Nothing 'turn on the screen updating when complete
Application.ScreenUpdating = False
Exit Sub
eh:
    MsgBox Err.Description
End Sub

Wrap-up: Merge CSV files in Excel

As a wrap-up, we decided to touch on how to merge CSV files in Excel. Actually, there is nothing complex since most of the methods above allow you to do this. Once you open a CSV file in Excel, it will look like a regular workbook, so you can use Power Query or VBA macros to merge them.

If your CSV files are stored online, you can easily merge them using Coupler.io in the same way we did with Excel files. The only difference is that you won’t need to select a sheet. Choose the best option for your needs and optimize your workflow as much as possible. Good luck with your data!

  • Zakhar Yung

    A content manager at Coupler.io whose key responsibility is to ensure that the readers love our content on the blog. With 5 years of experience as a wordsmith in SaaS, I know how to make texts resonate with readers’ queries✍🏼

Back to Blog

Focus on your business

goals while we take care of your data!

Try Coupler.io

Skip to content

Как быстро объединить несколько файлов Excel

Мы рассмотрим три способа объединения файлов Excel в один: путем копирования листов, запуска макроса VBA и использования инструмента «Копировать рабочие листы» из надстройки Ultimate Suite.

Намного проще обрабатывать данные в одном файле, чем переключаться между многочисленными книгами. Однако объединение нескольких книг Excel в один файл может быть сложным и долгим процессом, особенно если книги, которые вам нужно объединить, содержат много листов. Итак, как подойти к этой проблеме? Вы будете копировать их вручную или с помощью кода VBA? Или вы используете один из специализированных инструментов для объединения файлов Excel? 

Ниже вы найдете несколько хороших способов, позволяющих реализовать объединение.

  • Самое простое — копировать вручную.
  • Объединение файлов Excel при помощи VBA.
  • Как объединить несколько файлов с помощью Ultimate Suite.

Примечание. В этой статье мы рассмотрим, как копировать листы из нескольких книг Excel в одну книгу. Если вы ищете быстрый способ скопировать данные с нескольких листов на один общий лист, вы найдете подробную инструкцию в другой статье: Как объединить несколько листов в один.

Простой метод — копировать листы руками.

Если вам нужно объединить всего пару файлов Excel, вы можете вручную скопировать или переместить листы из одного файла в другой. Вот как это можно сделать:

  1. Откройте книги, которые мы планируем объединить.
  2. Выберите листы в исходной книге, которые вы хотите скопировать в основную книгу.

Чтобы выбрать несколько листов, используйте один из следующих приемов:

  • Чтобы выбрать соседние листы, щелкните вкладку первого, который вы хотите скопировать, нажмите и удерживайте клавишу Shift, а затем щелкните вкладку последнего. Это действие выберет все листы между ними.
  • Чтобы выбрать несмежные, удерживайте клавишу Ctrl и щелкайте вкладку каждого из них по отдельности.
  • Выделив все нужные листы, щелкните правой кнопкой мыши любую из выделенных вкладок и выберите «Переместить» или «Копировать…» .

  1. В диалоговом окне «Перемещение или копирование» выполните следующие действия:
    • В раскрывающемся списке «Переместить выбранные листы в книгу» выберите целевую книгу, в которую вы хотите объединить другие файлы.
    • Укажите, где именно должны быть вставлены вкладки. В нашем случае мы выбираем вариант вставки в конец списка.
    • Установите флажок «Создать копию», если хотите, чтобы исходные данные оставались оригинальном файле.
    • Нажмите ОК, чтобы завершить операцию.

Чтобы объединить вкладки из нескольких файлов Excel, повторите описанные выше шаги для каждой книги отдельно.

Замечание. При копировании листов вручную помните о следующем ограничении, налагаемом Excel: невозможно переместить или скопировать группу листов, если какой-либо из них содержит «умную» таблицу. В этом случае вам придется либо преобразовать таблицу в диапазон, либо использовать один из других методов, не имеющих этого ограничения.

Как объединить файлы Excel с VBA

Если у вас есть несколько файлов Excel, которые необходимо объединить в один файл, более быстрым способом будет автоматизировать процесс с помощью макроса VBA.

Ниже вы найдете код VBA, который копирует все листы из всех файлов Excel, которые вы выбираете, в одну книгу. Этот макрос MergeExcelFiles написан Алексом.

Важное замечание! Макрос работает со следующим ограничением — объединяемые файлы не должны быть открыты физически или находиться в памяти, в буфере обмена. В таком случае вы получите ошибку во время выполнения.

Sub MergeExcelFiles()
    Dim fnameList, fnameCurFile As Variant
    Dim countFiles, countSheets As Integer
    Dim wksCurSheet As Worksheet
    Dim wbkCurBook, wbkSrcBook As Workbook
 
    fnameList = Application.GetOpenFilename(FileFilter:="Microsoft Excel Workbooks (*.xls;*.xlsx;*.xlsm),*.xls;*.xlsx;*.xlsm", Title:="Choose Excel files to merge", MultiSelect:=True)
 
    If (vbBoolean <> VarType(fnameList)) Then
 
        If (UBound(fnameList) > 0) Then
            countFiles = 0
            countSheets = 0
 
            Application.ScreenUpdating = False
            Application.Calculation = xlCalculationManual
 
            Set wbkCurBook = ActiveWorkbook
 
            For Each fnameCurFile In fnameList
                countFiles = countFiles + 1
 
                Set wbkSrcBook = Workbooks.Open(Filename:=fnameCurFile)
 
                For Each wksCurSheet In wbkSrcBook.Sheets
                    countSheets = countSheets + 1
                    wksCurSheet.Copy after:=wbkCurBook.Sheets(wbkCurBook.Sheets.Count)
                Next
 
                wbkSrcBook.Close SaveChanges:=False
 
            Next
 
            Application.ScreenUpdating = True
            Application.Calculation = xlCalculationAutomatic
 
            MsgBox "Processed " & countFiles & " files" & vbCrLf & "Merged " & countSheets & " worksheets", Title:="Merge Excel files"
        End If
 
    Else
        MsgBox "No files selected", Title:="Merge Excel files"
    End If
End Sub

Как добавить этот макрос в книгу

Если вы хотите вставить макрос в свою книгу, выполните следующие обычные действия:

  1. нажимать Alt + F11 , чтобы открыть редактор Visual Basic.
  2. Щелкните правой кнопкой мыши ThisWorkbook на левой панели и выберите « Вставить» > « Модуль» в контекстном меню.
  3. В появившемся окне (Окно кода) вставьте указанный выше код.

Более подробная инструкция описана в разделе Как вставить и запустить код VBA в Excel .

Кроме того, вы можете загрузить макрос в файле Excel, открыть его в этой книге (включить выполнение макросов, если будет предложено), а затем переключиться на свою собственную книгу и нажать Alt + F8 для его запуска. Если вы новичок в использовании макросов в Excel, следуйте подробным инструкциям ниже.

Как использовать макрос MergeExcelFiles

Откройте файл Excel, в котором вы хотите объединить листы из других книг, и выполните следующие действия:

  1. Нажмите комбинацию Alt + F8, чтобы открыть окно диалога.
  2. В разделе « Имя макроса» выберите MergeExcelFiles и нажмите «Выполнить».

  1. Откроется стандартное окно проводника, вы выберите одну или несколько книг, которые хотите объединить, и нажмите «Открыть» . Чтобы выбрать несколько файлов , удерживайте нажатой клавишу Ctrl, указывая на их имена.

В зависимости от того, сколько файлов вы выбрали, дайте макросу несколько секунд или минут для их обработки. После завершения всех операций он сообщит вам, сколько файлов было обработано и сколько листов было объединено:

Как объединить несколько файлов с помощью Ultimate Suite.

Если вам не очень комфортно с VBA и вы ищете более простой и быстрый способ объединить файлы Excel, обратите внимание на инструмент «Копирование листов (Copy Sheets)» — одну из более чем 60 функций, включенных в невероятно функциональную программу Ultimate Suite for Excel. Она работает в версиях Excel 2010-2019.

С Ultimate Suite объединение нескольких файлов Эксель в один так же просто, как раз-два-три (буквально, всего 3 быстрых шага). Вам даже не нужно открывать те из них, которые вы хотите объединить. И это могут быть два файла или несколько — не важно.

  1. Открыв главную книгу, перейдите на вкладку «Ablebits Data» и нажмите «Копировать листы (Copy Sheets)» > «Выбранные в одну книгу (Selected Sheets to one workbook)».

  1. В диалоговом окне выберите файлы (а в них — листы), которые вы хотите объединить, и нажмите «Далее (Next)» .

Советы:

  • Чтобы выбрать все листы в определенной книге, просто поставьте галочку в поле рядом с именем книги, и все они в этом файле будут выбраны автоматически.
  • Чтобы объединить листы из закрытых книг, нажмите кнопку «Добавить файлы…» и выберите столько книг, сколько нужно. Это добавит выбранные файлы только в окно копирования, не открывая их в Excel.
  • По умолчанию копируются все данные. Однако, в разных листах можно выбрать разные диапазоны для объединения. Чтобы скопировать только определенную область, наведите указатель мыши на имя вкладки, затем щелкните значок    и выберите нужный диапазон. 
  • При необходимости укажите один или несколько дополнительных параметров и нажмите «Копировать» . На снимке скриншоте а ниже показаны настройки по умолчанию: Вставить все (формулы и значения) и Сохранить форматирование.

Дайте мастеру копирования листов несколько секунд для обработки и наслаждайтесь результатом!

На этой странице есть подробное описание всех возможностей работы мастера копирования.

Чтобы поближе познакомиться с этим и другими инструментами для Excel, вы можете загрузить ознакомительную версию Ultimate Suite.

Итак, я надеюсь, вы получили ответ на вопрос — как быстро объединить несколько файлов Excel в один.

Bookmark this app

Press Ctrl + D to add this page to your favorites or Esc to cancel the action.

Send the download link to

Send us your feedback

Oops! An error has occurred.

Invalid file, please ensure that uploading correct file

Error has been reported successfully.


You have successfully reported the error, You will get the notification email when error is fixed.

Click this link to visit the forums.

Immediately delete the uploaded & processed files.

Are you sure to delete the files?

Enter Url

Like this post? Please share to your friends:
  • How to merge data in excel
  • How to merge cells with excel
  • How to measure word
  • How to mark the text in word
  • How to mark stress in a word