Multiple excel files to one

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 в один.

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.

How Do I Combine Multiple Files Into One File?

Do you need to combine multiple Excel files? Maybe you have many different Excel workbooks that you’re working on, and you want to manage in one place. Perhaps you want one master spreadsheet referencing a few other ones. Maybe you shared a copy of the Excel file with your team, who updated parts of it, and you want to merge it back into the master file.

There are many methods to combine Excel files. Each method can be useful in its own way, depending on your use case. So without further ado, let’s go through some of the most popular methods to merge Excel files.

If you want to combine data from multiple Google Sheets, you can do that easily using Layer. Layer is a free add-on that allows you to share sheets or ranges of your main spreadsheet with different people. On top of that, you get to monitor and approve edits and changes made to the shared files before they’re merged back into your master file, giving you more control over your data.

Install the Layer Google Sheets Add-On today and Get Free Access to all the paid features, so you can start managing, automating, and scaling your processes on top of Google Sheets!

What Are XLS Files?

XLS files are Microsoft Excel spreadsheet documents that store data in worksheets, which contain cells arranged into rows and columns. XLS stands for eXceL Spreadsheet. XLS files can contain numerical data, text, charts, and even audio and video. They are used for creating spreadsheets that can be modified and updated with ease. The .xls file extension is the most common format for Excel documents created using Microsoft Office 97-2003 or earlier versions of the software. In newer versions of Microsoft Office, XLS files are replaced by the Excel Workbook format (.xwb).

XLS files are widely used in businesses and educational institutions, as they allow large amounts of data to be organized and shared easily. Excel spreadsheets can be used for a variety of purposes, such as creating budgets, tracking sales figures, analyzing survey results, and more. XLS files can also be opened in other spreadsheet programs such as OpenOffice Calc, Apple Numbers, and Google Sheets.

XLS files are cross-platform compatible, meaning they can be opened on Mac, Windows, and Linux operating systems. To open an XLS file you will need a program that can read Excel documents such as Microsoft Excel, Apache OpenOffice Calc, Apple Numbers, or Google Sheets.

How to Combine Excel Files With Manual Copying?

Copy Paste

The easiest and most straightforward way to merge two files is to simply copy the data from one file to another.

  1. 1. Select the range to copy or press Ctrl/Cmd + A to select the entire sheet.
  2. 2. Press Ctrl/Cmd + C to copy the range.
  3. 3. Head to the other spreadsheet and, if necessary, create a new sheet.
  4. 4. Select the location to paste the data and press Ctrl/Cmd + V.

While this method might be the fastest when dealing with smaller spreadsheets, it becomes risker and more complicated as the files grow. Human error is almost inevitable, and mistakes are bound to happen. That’s why you should only use this method for simple personal use cases.

How to Combine Excel Files Using Move or Copy?

Move or Copy

You can use Excel’s «Move or Copy» feature to copy one or more Excel sheets from one Workbook to another instantly.

  1. 1. Open the Excel files.
  2. 2. Select the sheets you want to copy to the other Workbook by holding Ctrl/Cmd and selecting the sheets. The selected sheets will be highlighted. You can unselect sheets by clicking on them again.
  3. 3. To select multiple sheets at once, head to the first sheet you want to copy and hold the Shift key. Then, select the last sheet to copy. All the sheets between the two selected ones will be selected as well.
  4. 4. Right-click and select «Move or Copy». A dialog box will pop up.

Move or Copy

  1. 5. Under «To book:», select the other file to move the data to.
  2. 6. For «Before sheet:», select where you want the sheets to be inserted. You can always re-organize your sheets later.
  3. 7. Press «Ok».

How to Combine Excel Files By Pasting Links?

Paste Link

Excel allows you to reference cells in different Excel files or workbooks. This makes it possible to combine Excel files by referencing them in the master file.

  1. 1. Open both Excel files.
  2. 2. Copy the first cell from the Workbook you want to reference.
  3. 3. Go to your master file.
  4. 4. Select the cell where you want to display the data and press right-click.
  5. 5. From the menu, select Paste Special > Paste Link. This will automatically generate the necessary formula for you. It will look like this:
='[file.xlsx]sheet'!$A$1
  1. 6. To display the other cells, change the formula from absolute cell referencing to relative cell referencing by removing the dollar signs ($) so that it looks like:
='[file.xlsx]sheet'!A1
  1. 7. Copy and paste the formula to the other cells that you want to display.

While this method allows you to protect your data by only using references to your files instead of pasting the values, it can be overly complicated. If you break one of the formulas or accidentally delete one of the files, you will end up with many #REF! errors that may be hard to fix.

In addition, when referencing blank cells, while you might think that they would stay empty, the cells will display a zero «0» in the master sheet. There are, of course, workarounds for this to hide the zeros in this case, but it’s yet another additional step that makes this method even more complicated.

How to Combine Excel Files Using Power Query?

Power Query (Get & Transform) allows you to import, edit, and consolidate data into Excel. It can also be used to combine multiple Excel files by adding them to one folder:

  1. 1. Move all of the files you want to combine into one folder.
  2. 2. In Excel, go to the «Data» tab.
  3. 3. Press Get Data > From File > From Folder.
  4. 4. Browse and select the folder path.
  5. 5. Press «Ok».
  6. 6. If the files are ready to be combined, press «Combine & Load».
  7. 7. If you wish to manipulate the data before combining the files, press the «Transform Data» button. This will open up the Query Editor, where you will have the ability to re-organize and filter data, manage rows and columns, and more.

The Get & Transform method might be one of the easiest to combine files from multiple sources together. Not only does it allow you to import Excel Workbooks, but you can also import other file formats, including text, CSV, XML, JSON, PDF, and more.

However, this feature is only available in all Excel 2016 or later Windows stand-alone versions and Microsoft 365 subscription plans. This means that Mac users are unable to use this feature and instead will need to use VBA.

How to Combine Excel Files Using VBA?

VBA

Excel VBA (Visual Basic for Applications) is the programming language for Excel and all Microsoft Office products. It allows you to create macros to manipulate and automate your Excel processes.

Don’t worry. You won’t have to learn a new programming language. You can use the pre-created macros below. And while we won’t be going into details regarding VBA, you can find descriptions for each part of the macros below.

  1. 1. Open all the Excel files that you want to combine.
  2. 2. To open the VBA editor, use the Windows shortcut Alt + F11 or the Mac shortcut Opt + F11 or Fn + Opt + F11.
  3. 3. Go to Insert > Module. This will create a new module for the Workbook.
  4. 4. Copy and paste one of the codes below depending on the way you want to combine your spreadsheets:

Combine all Excel files into a new workbook as individual sheets

Sub CombineMultipleFiles()
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
    'now close all the open files except the new file and the Personal macro workbook.
For Each wb In Application.Workbooks
If wb.Name < > strDestName And wb.Name < > "PERSONAL.XLSB"
Then
wb.Close False
End If
Next wb

    'remove sheet one from the destination workbook
Application.DisplayAlerts = False
Sheets("Sheet1").Delete
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

Combine all Excel files into a single sheet in a new workbook

Sub CombineMultipleSheets()
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
'now close all the open files except the one you want
 For Each wb In Application.Workbooks
 If wb.Name <> strDestName And wb.Name <> "PERSONAL.XLSB" Then
 wb.Close False
 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

Combine all Excel files into a single worksheet in an active workbook

Sub CombineMultipleSheetsToExisting()
 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
'now close all the open files except the one you want
 For Each wb In Application.Workbooks
 If wb.Name <> strDestName And wb.Name <> "PERSONAL.XLSB" Then
 wb.Close False
 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

5. 5. Press the play button. This will open the «Macros» dialogue box.
6. 6. Select the macro and press «Run».

While VBA can be extremely powerful, again, it’s a programming language. This means that besides using pre-written macros, you would have to learn Excel VBA to create your own or modify existing ones, which comes with its own set of challenges.

Highlight changes

Excel’s legacy Shared Workbook feature allows. While Excel eventually replaced it with its new co-authoring feature due to its many limitations, you can still use it to merge shared copies of the same Excel file.

First, you will need to enable highlighting changes:

  1. 1. Go to Tools > Track Changes > Highlight changes.
  2. 2. Check the «Track changes while editing» box to enable tracking.
  3. 3. Select when you want to start highlighting changes, for whom, and for which cell range, if necessary. By leaving the boxes unchecked, you will be tracking all the changes in your Workbook for all collaborators.
  4. 4. Select whether you want to enable onscreen highlighting, which outlines affected cells in different colors for different users. This is only useful for workbooks with few changes as it only provides a rudimentary glance at the changes.

How to Merge Versions of a Shared Excel Workbook

Excel’s legacy Shared Workbook feature allows. While Excel eventually replaced it with its new co-authoring feature due to its many limitations, you can still use it to merge shared copies of the same Excel file.

First, you will need to enable highlighting changes:

  1. 1. Go to Tools > Track Changes > Highlight changes.
  2. 2. Check the «Track changes while editing» box to enable tracking.
  3. 3. Select when you want to start highlighting changes, for whom, and for which cell range, if necessary. By leaving the boxes unchecked, you will be tracking all the changes in your Workbook for all collaborators.
  4. 4. Select whether you want to enable onscreen highlighting, which outlines affected cells in different colors for different users. This is only useful for workbooks with few changes as it only provides a rudimentary glance at the changes.

How to Share an Excel File for Multiple Users?

There are different ways to share an Excel file. Here’s how to share an Excel file with multiple users for easy collaboration

READ MORE

How to Share an Excel File for Multiple Users

To merge two different versions or copies of the same Excel workbook:

  1. 1. Go to Tools > Merge Workbooks.
  2. 2. Select the Excel file you want to merge with your current one. The Workbook selected must be a copy made from the same shared Workbook and must maintain change history for a sufficient amount of time to be able to merge them.
  3. 3. Press «Ok».

The data from the selected version of the spreadsheet will be applied to your current one. If the «Track Changes» feature is turned on, the changes will be highlighted for you to review and choose whether to accept or reject them.

Unfortunately, the Shared Workbook feature has many limitations, which is why it was discontinued by Excel and replaced by their co-authoring feature. The feature lacks support for many of Excel’s items and actions like creating or inserting tables, inserting or deleting blocks of cells, deleting worksheets, inserting or changing hyperlinks, and much more.

That’s why it’s recommended that you use a spreadsheet management platform like Layer.

Want to Boost Your Team’s Productivity and Efficiency?

Transform the way your team collaborates with Confluence, a remote-friendly workspace designed to bring knowledge and collaboration together. Say goodbye to scattered information and disjointed communication, and embrace a platform that empowers your team to accomplish more, together.

Key Features and Benefits:

  • Centralized Knowledge: Access your team’s collective wisdom with ease.
  • Collaborative Workspace: Foster engagement with flexible project tools.
  • Seamless Communication: Connect your entire organization effortlessly.
  • Preserve Ideas: Capture insights without losing them in chats or notifications.
  • Comprehensive Platform: Manage all content in one organized location.
  • Open Teamwork: Empower employees to contribute, share, and grow.
  • Superior Integrations: Sync with tools like Slack, Jira, Trello, and more.

Limited-Time Offer: Sign up for Confluence today and claim your forever-free plan, revolutionizing your team’s collaboration experience.


  • — By
    Sumit Bansal

I got a call from a friend who wanted to combine multiple Excel files into one Excel workbook. He had a lot of files in a folder and he wanted to get all the worksheets from all the workbooks into one single workbook.

While this can be done manually, it would be time-consuming and error-prone.

However, a simple VBA code can do this in a few seconds.

Combine Multiple Workbooks into One Excel Workbook - Image Orange

Combine Multiple Excel Files into One File

Here is the code that can combine multiple Excel workbooks in a specified folder into a single Excel workbook:

Sub ConslidateWorkbooks()
'Created by Sumit Bansal from https://trumpexcel.com
Dim FolderPath As String
Dim Filename As String
Dim Sheet As Worksheet
Application.ScreenUpdating = False
FolderPath = Environ("userprofile") & "DesktopTest"
Filename = Dir(FolderPath & "*.xls*")
Do While Filename <> ""
 Workbooks.Open Filename:=FolderPath & Filename, ReadOnly:=True
 For Each Sheet In ActiveWorkbook.Sheets
 Sheet.Copy After:=ThisWorkbook.Sheets(1)
 Next Sheet
 Workbooks(Filename).Close
 Filename = Dir()
Loop
Application.ScreenUpdating = True
End Sub

How to Use this Code?

Here are the steps to use this code:

This will run the code and all the worksheets from all the Excel files in the folder would get consolidated into a single workbook.

Combine Multiple Excel files into One Excel Workbook - demo

How this Code Works?

  • The code uses the DIR function to get the file names from the specified folder.
  • The following line assigns the first excel file name to the variable ‘Filename’.
    Filename = Dir(FolderPath & “*.xls*”)
  • Then the Do While loop is used to check whether all the files have been covered.
  • Within the ‘Do While’ loop, ‘For Each’ loop is used to copy all the worksheets to the workbook in which we are running the code.
  • At the end of the Do Loop, following line of code is used: Filename = Dir(). It assigns the next Excel file name to the Filename variable and the loop starts again.
  • When all the files are covered, DIR function returns an empty string, which is when the loop ends.

Here is an explanation of the DIR function in the MSDN library:

Dir returns the first file name that matches pathname. To get any additional file names that match pathname, call Dir again with no arguments. When no more file names match, Dir returns a zero-length string (“”).

Have you ever tried something of this sort using VBA? Do share what you did and we all can learn from it.

Save Crazy Amount of Time Using VBA. Check out the Excel VBA COURSE.

You May Also Like the Following Excel Tutorials:

  • How to Combine Data from Multiple Workbooks into One Excel Table (using Power Query).
  • Quickly Create Summary Worksheet with Hyperlinks in Excel.
  • How to Create and Use an Excel Add-in.
  • How to Run a Macro.
  • 20 Useful Excel Macro Examples.

Excel Ebook Subscribe

Get 51 Excel Tips Ebook to skyrocket your productivity and get work done faster

98 thoughts on “How to Combine Multiple Excel Files into One Excel Workbook”

  1. Brilliant thanks!

  2. Highly frustrating – simply can’t get the damn thing to work….

    • I had this problem as well but fixed it as follows,

      1. Save the document as .xlxm
      2. Make sure you have a “/” at the end of your directory path

      • sorry .xlsm

  3. The code works but the filepath string requires all of the “” in the complete file path. For example: C:UsersUser1DesktopExcelfiles*.xls*. This best way to solve this is:

    When you modify the FolderPath = Environ(“userprofile”) & “DesktopTest” make sure you include the pre and post forward slashes “” to the folder path containing the excel sheets to be imported.

    When you are debugging right click on the Folderpath and Filename variable and set them to the Watchlist with the Break when value changes box checked. When you run the program you can verify those two variables are updating correctly.

  4. Thanks so much, worked perfectly.

  5. Not working,It is showing debugg at Filename = Dir(FolderPath & “*.xlsx*”).
    Can you please provide a fix

  6. For this code to work some of you will likely need more than the suggested file path of:

    FolderPath = Environ(“userprofile”) & “DesktopTest”

    Environ(“userprofile”) will only provide the first part of a filepath. In my case it was: C:UsersWF. There were several subfolders “along the path” before getting to the folder I used for the files to be combined. Use this example as the path to the correct folder:

    folderpath = “C:UsersWFDocumentsFolder1Folder2Folder3FolderWithFiles

    For a convenient way to get the correct path use this code to place the path on a worksheet. Then copy/paste into the sub procedure.

    Sub Path_FileName()
    Dim strPath As String
    strPath = ActiveWorkbook.FullName
    ActiveCell.Value = strPath
    End Sub

    Make this adjustment if you need to. This is some very useful code.

  7. I was getting error 52 as well.

    “DESKTOP TEST” = LOCATION OF FILE

    I changed this string of code (moved the parenthesis) from the below and it worked:

    CHANGED FROM
    FolderPath = Environ(“userprofile”) & “DesktopTest”

    CHANGED TO
    FolderPath = Environ(“userprofile” & “DesktopTest”)

  8. Big thank you!! I had found various other versions of this code but this is the first one that worked for my version of Excel. Needed to combine over 30 spreadsheets and it saved me lots of time!

  9. I am getting error 52 when I run the code.

  10. Thanks alot. It was very helpful. I am a options trader needed it to backtest the things. So thanks again. Let me know how can I give it back to you.

  11. Many thanks for this! Forty spreadsheets … into one without copy/pasting each sheet. Phew.

  12. how can i add in the header in the active worksheet before I run this code? or i can do it at the same time?

  13. I have followed the instructions carefully but i get an error of Bad filename 52

  14. Great code and works! One thing though that may be tripping people up. The string Filename also is part of the Workbooks.Open Filename:= command. Anyone having issues with the Filename variable should try attempting to rename the string to something else to avoid issues. Least what I had to do for this to properly work for me.

    • I am having filename issues

  15. fabulous!!! works amazing

  16. Filename = Dir(FolderPath & “*.xls*”)

  17. Sorry not working for me, gives me error on file dir.

  18. Cant combine multiple files…no error shown,can we send you the sample files-please share your email id

  19. Worked for me. Thank you so Much! saved me much time for a work project. Thank you so much for uploading

  20. Like so many in this thread, this did not work for me – suggest it is taken down as a waste of valuable time!

  21. That worked amazing! Thank you, thank you, thank you!

  22. Heaps thanks worked just perfect.. you saved my time.

  23. Hi , how can I combine the first worksheet of multiple Excel workbooks in a specified folder into a single Excel workbook ?

  24. I have used this code but its is creating multiple tabs for the sheet with same name like Name (1); Name(2); Name(3)

    Any solution

  25. I am getting Run-time error Bad file name or number
    I have used the path “H:Sheets”
    Please advise

    • Delete the :

  26. it didnt work, this came back as an error
    Filename = Dir(FolderPath & “*.xls*”)

    • have you solve this case ? I have same error …

    • try putting “” at the end of folder path (note that in dos, between file name and the directory there has to be “” sign

  27. I want to combine individual timesheets into one master file, but the t/s are protected. Will I still be able to enter data and save it?

  28. I am getting debug in filename. Please help me

    • Remove the Environ(“userprofile”) & from your code. This just tells VBA to go to folders under your user. But if you already have something like “C:UsersVarunDocuments” in the folder path, this will throw the error you get.

  29. Excellent !!!

    Is it possible to name the sheets accordingly to their filenames?

    • Hi, i am getting debug in Filename.
      Can you help me ?

  30. Hie I have many workbook and i want to combine every second sheet from workbook together

  31. Thanks for this tip Sumit………….

    But it create multiple sub sheets of multiple files…what should to do if we need all multiple files into only one single sub sheet and i also want that the data copy should be in sequence

  32. Not working for me. I followed all the steps mentioned above.

    • juse WPS office

    • sorry i just want to say. Use WPS Office

  33. error 1004:
    method ‘copy’ of object ‘ _worksheet’ failed

    Debug =

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

    • Same issue with me.

  34. not working this coding,
    error on
    Filename = Dir(FolderPath & “*.xls*”)
    kindly slove this problem

    • I am getting the same error

    • I used ” ” and entered folder path where the file is located inside the quotation and it worked for me.

  35. Hi I need some help in developing an extinction tool. Where 80 Percent can be done through formulas. Bit I need some help on remaining things. Will appreciate your help.

  36. not working 🙂
    need smart support

    • I am making an estimation tool. The first method worked, but that’s not dynamic.
      I want the list to refresh if a new file is added to the folder.

  37. Thanx a lot !!!!! Saved lot of time

  38. Super!!!
    Saved lot of time

  39. hi can i update daily log sheets / material use sheet, warehouse sheet and combining into 1 for KPI ? daily folks save in same folder with different date and shift

  40. Hi Sumit
    It does’nt work for me after peressing the F5 I got ERE “BAD FILE NAME”
    As I see numer of people here have had the same ERE plz explain the reason for it

  41. What about copying different sheets from different excel files to one sheet by adding the new data to the old one ?

  42. Thank you so much for this VBA code! Excellent time-saver!

  43. Hi, I have to copy 4 sheets from different excel files in one excel.
    Excel name in which i have to copy my data= Summary

    Data copy from below listed excels
    Excel 1= Los Angeles CCAP ASE Job Log Backup 15-11-18
    Excel 2= Anaheim CCAP ASE Job Log Backup 15-11-18
    Excel 3= BAY-North CCAP ASE Job Log Backup 15-11-18
    Excel 4= San Diego CCAP ASE Job Log Backup 15-11-18

    Now from every file, I have to copy only 1 sheet. names of sheets are mentioned below.
    Excel 1 sheet name= LA
    Excel 2 sheet name= Anaheim
    Excel 1 sheet name= SD
    Excel 1 sheet name= BayNorth

    Please help I have to submit a report to my manager.

  44. I have over 2000 files to combine. I did a test run of 100 and the result was garbage.

    • Did you ever find a solution? I am in a similar boat.

  45. how to combine three workbook in one workbook easy and quick

  46. I am getting error mentioning Run time error 52. Bad file name or number. For your information I have saved the files on my Desktop with a folder name as Test. Please suggest

  47. I am getting an error as bad file name,can someone help me with this error,would be really thankful!

  48. It doesn’t work for me, I have “bad file name or number”. do you know how to fix it?

  49. helpful

  50. very useful ,I like it very much !

  51. When i press f5, nothing happens -! can anyone pls help ?

  52. Attempting with CSV files. =) will let you know.

  53. I have a query . Suppose I have to merge 652 workbooks into one. The filenames are 1.xlsx to 652.xlsx and i want to merge them in ascending order of their filenames only . Will this code merge it according to their sorted name in the folder or not ??

  54. Hi Sumit, need your assistance with the above macro.

    This works good if you want to combine multiple sheets in 1 workbook.

    I need a solution where the following steps need to be done :

    1. There are around 4000 employees and the workbook will be each employee code wise
    2. There are 18 folders with workbooks with 1 worksheet for each employee.. there is a possibility that for an employee one of the workbooks will not be there
    3. The macro should create a workbook with the emp code then across the 18 folders should check whether workbook is available for the employee ID and if yes
    4. Copy and paste it in the created workbook and save.
    5. Additionally there are 3 workbooks by default which need to be added for all employees

    What i do not know to edit the above macro is:

    1. How do i build a For loop for an employee list
    2. If there is no specific excel workbook in one of the folder then it should not throw an error

    Please help. I can communicate on your official email id too and will be happy if you can provide a solution at the earliest even if it is chargeable.

    Regards

  55. That’s great thanks. It would be even better if it named the sheets after the original file names.

    • yes

  56. Still usable. You need to place a “/” after your path if you copy it in.

    • Thank you, this worked along with removing the Environ(“userprofile”) & code segment for FolderPath where I was able to combine 13 single sheet Excel files that I placed in a test folder on a mapped network drive (example: FolderPath = “Z:20198 – AUGMeeting AttendeesTest/”

  57. The code is really work for me using in Excel 2016 after few experiments.
    Some tips for those who are struggling about getting error message:
    1) The code is worked for both xls and xlsx, don’t need to modify it.
    2) The code ONLY works for worksheet, do try to move chart, you will get error. (anyone know how to move all together?)
    3) Try 1 or 2 workbooks first to see whether it is work for you or not.

    Hope these help you all 🙂

  58. Wow first one actually worked:)

  59. This did not work. Yes it combines 2 workbooks, but it destroys the functionality of the formulas in the process. Now, this could be me making some bad choices when it prompts me while the macro is running. Idk. Example: while macro was running I got several “name ‘use lists’ already exists. Yes to keep no to rename it something else” messages (sub ‘use lists’ with various other names). And regarding other formulas being destroyed, example: a simple =’TAB’!A1&” “&’TAB’!A2 type of formula is now bloated with file directory info. So it reads like:
    =’C:UserEtcpathTAB’!A1&” “&’C:UserEtcpathTAB’!A2
    That last one I can fix by deleting the stupid file directory info, formula by formula. As for the whole yes or no to renaming stuff that already exists… I’m at a loss.

    TL;DR I don’t know VBA & this formula didn’t work in my scenario.

  60. Sumit Bansal you Rock <3

  61. Thanks for posting this! I’m getting “Run-time error ’52’: Bad file name or number” – anyone know how I can overcome this?

    • change .xls to .xl
      I removed the “environment” as well

  62. Need multiple files into one single sheet.

  63. Hi, I was able to get the script above to work.

    How can I modify this script to combined Sheets with the name “Sheet1” from multiple file into one file.

    • so how did you ended up making it work???

  64. What am I missing? I keep getting a run time error 52 (bad file name or number) on this line: Filename = Dir(FolderPath & “*.xlsm*”). I changed it to .xlsm for Excel 2013 for macro.

    • Ugh…me too!!!

  65. also, can I only combine page 1 of the workbooks to be combined into a single workbook?

  66. If my files are on a network drive, do I remove the “Environ” part of the FolderPath?

  67. It’s not working for me..!! When i am pressing F5…no combination of sheets..>!!

  68. Thank you for the tip.
    I have a question related to the handling the files with macros (*.xlsm) since the code will pick these files as well during the run. It seems that the macros will not be copied along with the worksheets and therefore some of the formulas may not work in the new workbook.

    • Thanks for commenting Lazarus.. You’re right! This wouldn’t pick up the macros while copying the sheets

      • is there any way if the multiple files can be consolidated into one single tab instead of multiple tabs?

      • Hi Sumit,
        Also it is not working for me for “xlsx” file. It is showing debugg at Filename = Dir(FolderPath & “*.xlsx*”). Please get a solution. Thanks

        • I am getting the same error…..

          • Here When the Path In the Folder Is Copied It Must Start Form The “Desktop” & Not As “C:”

            If Rectify This Then It Automatically Works When pressing “F5”

        • Here When the Path In the Folder Is Copied It Must Start Form The “Desktop” & Not As “C:”
          If Rectify This Then It Automatically Works When pressing F5

  69. Thanks for this tip Sumit………….

    But it create multiple sub sheets of multiple files…what should to do if we need all multiple files into only one single sub sheet…………

    Pls. help.

    • Hello Anand, By what I understand, You want to combine all the sheets from all the workbooks into a single sheet. This may be limited by the number of rows in a worksheet. It would be helpful if you could share a sample file

      • Hi Sumit,

        Firstly Thanks for concern.

        I have send an email to you for further clarification on it. Pls. have a look.

        • Hi Sumit………..

          Pls. help on this…………

Comments are closed.

Понравилась статья? Поделить с друзьями:
  • Multiple copy in excel
  • Multiple conditioning in excel
  • Multiple columns to one column in excel
  • Multiple choice quiz in word
  • Multiple choice questions in word