Merging sheets in excel

Excel for Microsoft 365 for Mac Excel 2021 for Mac Excel 2019 for Mac Excel 2016 for Mac Excel for Mac 2011 More…Less

If you receive information in multiple sheets or workbooks that you want to summarize, the Consolidate command can help you pull data together onto one sheet. For example, if you have a sheet of expense figures from each of your regional offices, you might use a consolidation to roll up these figures into a corporate expense sheet. That sheet might contain sales totals and averages, current inventory levels, and highest selling products for the whole enterprise.

To decide which type of consolidation to use, look at the sheets you are combining. If the sheets have data in inconsistent positions, even if their row and column labels are not identical, consolidate by position. If the sheets use the same row and column labels for their categories, even if the data is not in consistent positions, consolidate by category.

Combine by position

For consolidation by position to work, the range of data on each source sheet must be in list format, without blank rows or blank columns in the list.

  1. Open each source sheet and make sure that your data is in the same position on each sheet.

  2. In your destination sheet, click the upper-left cell of the area where you want the consolidated data to appear.

    Note: Make sure that you leave enough cells to the right and underneath for your consolidated data.

  3. On the Data tab, in the Data Tools group, click Consolidate.

    The Consolidated button on the Data tab

  4. In the Function box, click the function that you want Excel to use to consolidate the data.

  5. In each source sheet, select your data.

    The file path is entered in All references.

  6. When you have added the data from each source sheet and workbook, click OK.

Combine by category

For consolidation by category to work, the range of data on each source sheet must be in list format, without blank rows or blank columns in the list. Also the categories must be consistently labeled. For example, if one column is labeled Avg. and another is labeled Average, the Consolidate command will not sum the two columns together.

  1. Open each source sheet.

  2. In your destination sheet, click the upper-left cell of the area where you want the consolidated data to appear.

    Note: Make sure that you leave enough cells to the right and underneath for your consolidated data.

  3. On the Data tab, in the Data Tools group, click Consolidate.

    The Consolidated button on the Data tab

  4. In the Function box, click the function that you want Excel to use to consolidate the data.

  5. To indicate where the labels are located in the source ranges, select the check boxes under Use labels in: either the Top row, the Left column, or both.

  6. In each source sheet, select your data. Make sure to include either the top row or left column information that you previously selected.

    The file path is entered in All references.

  7. When you have added the data from each source sheet and workbook, click OK.

    Note: Any labels that don’t match labels in the other source areas cause separate rows or columns in the consolidation.

Combine by position

For consolidation by position to work, the range of data on each source sheet must be in list format, without blank rows or blank columns in the list.

  1. Open each source sheet and make sure that your data is in the same position on each sheet.

  2. In your destination sheet, click the upper-left cell of the area where you want the consolidated data to appear.

    Note: Make sure that you leave enough cells to the right and underneath for your consolidated data.

  3. On the Data tab, under Tools, click Consolidate.

    Data tab, Tools group

  4. In the Function box, click the function that you want Excel to use to consolidate the data.

  5. In each source sheet, select your data, and then click Add.

    The file path is entered in All references.

  6. When you have added the data from each source sheet and workbook, click OK.

Combine by category

For consolidation by category to work, the range of data on each source sheet must be in list format, without blank rows or blank columns in the list. Also the categories must be consistently labeled. For example, if one column is labeled Avg. and another is labeled Average, the Consolidate command will not sum the two columns together.

  1. Open each source sheet.

  2. In your destination sheet, click the upper-left cell of the area where you want the consolidated data to appear.

    Note: Make sure that you leave enough cells to the right and underneath for your consolidated data.

  3. On the Data tab, under Tools, click Consolidate.

    Data tab, Tools group

  4. In the Function box, click the function that you want Excel to use to consolidate the data.

  5. To indicate where the labels are located in the source ranges, select the check boxes under Use labels in: either the Top row, the Left column, or both.

  6. In each source sheet, select your data. Make sure to include either the top row or left column information that you previously selected, and then click Add.

    The file path is entered in All references.

  7. When you have added the data from each source sheet and workbook, click OK.

    Note: Any labels that don’t match labels in the other source areas cause separate rows or columns in the consolidation.

Need more help?

Want more options?

Explore subscription benefits, browse training courses, learn how to secure your device, and more.

Communities help you ask and answer questions, give feedback, and hear from experts with rich knowledge.

Let’s assume you have many worksheets, all in the same structure. Or they are at least in a similar structure. Now, you want to combine them into one worksheet. For example copying them underneath each other so that you can conduct lookups or insert PivotTables. In this article, you learn four methods to merge sheets in Excel.

Method 1: Copy and paste worksheets manually

In many cases it’s probably the fastest way to just copy and paste each sheet separately. That depends of course on the number of worksheets you want to combine and their structure. Some comments:

  • Try to use keyboard shortcuts as much as possible. For example for selecting the complete worksheet (Ctrl + A), copying the data (Ctrl + C), navigating to your combined worksheet (Ctrl + Page Up or Page Down) and pasting the copied cells (Ctrl + V).
  • Also the shortcut of pressing Ctrl on the keyboard and clicking on the little arrow in the left bottom corner of your worksheet could help. That way you jump to the first or last worksheet in your Excel workbook.
  • This method is especially useful if you just have to merge sheets once. If you need to do it repeatedly (for example you get new inputs every week or month) it’s probably better to check out methods 2 to 4 below.

Method 2: Use the INDIRECT formula to merge sheets

You can use Excel formulas to combine data from all worksheets. The main formula is INDIRECT.

This method has some disadvantages, though.

  • The INDIRECT formula in general is slow because it’s volatile. That means, it calculates each time Excel calculates something.
  • Using a combination of INDIRECT is usually unstable and error prone.
  • It takes some work to set up the INDIRECT formula.

On the other hand, it has one major advantage: If you spend effort to set it up, this method is dynamic. That means when your input updates, the merged worksheet updates as well.

Approach

Merge Sheets: Set up the INDIRECT formula for merging sheets.
Set up the INDIRECT formula for merging sheets.

The INDIRECT formula can access any cell from a link (or better: an address) you provide. Please refer to this article to learn more about the INDIRECT formula. So you only have to provide the addresses for each cell in each worksheet you want to combine. Therefore, you should prepare a worksheet the following way (please refer to the screenshot on the right-hand side):

  • Column A contains the sheet name.
  • Column B contains the row number.
  • Starting from Column C, you should add the column letters.

So let’s assume that you want to get the value from cell A1 of Sheet1. You would need then all the parts ‘Sheet1’, column ‘A’ and row ‘1’. Combining them in the INDIRECT formula would lead to the following formula. The formula in cell C4 is =INDIRECT(“‘”&$A4&”‘!”&C$2&$B4) .

Download

download, arrow
Merge Sheets: Copy this worksheet into your Excel file and all sheets are merged automatically.
Copy this worksheet into your Excel file and all sheets are merged automatically.

You want to save some time? We prepared a worksheet which can merge sheets automatically. What do you have to do? Download this workbook (~7 MB) and copy the only sheet into your own workbook. That’s it.

Please note the following comments.

  • This method requires to enable macros (a list of all worksheets in your workbook is automatically created). When you want to save your workbook, you will be asked to switch to the XSLM file format.
  • This model works for up to 50 sheets with 200 rows each (10,000 cells are prepared). If you need more, you have to extend it. The reason for this restriction is that the file is already quite large and requires some calculation performance.

Method 3: Merge sheets with a VBA Macro

You feel confident enough to use a simple VBA macro? Please insert the following code into a new VBA module. If you need assistance with VBA, please refer to this article.

Sub Merge_Sheets()
    'Insert a new worksheet
    Sheets.Add
    
    'Rename the new worksheet
    ActiveSheet.Name = "ProfEx_Merged_Sheet"
    
    'Loop through worksheets and copy the to your new worksheet
    For Each ws In Worksheets
        ws.Activate
        
        'Don't copy the merged sheet again
        If ws.Name <> "ProfEx_Merged_Sheet" Then
            ws.UsedRange.Select
            Selection.Copy
            Sheets("ProfEx_Merged_Sheet").Activate
            
            'Select the last filled cell
            ActiveSheet.Range("A1048576").Select
            Selection.End(xlUp).Select
            
            'For the first worksheet you don't need to go down one cell
            If ActiveCell.Address <> "$A$1" Then
                ActiveCell.Offset(1, 0).Select
            End If
            
            'Instead of just paste, you can also paste as link, as values etc.
            ActiveSheet.Paste
        
        End If
        
    Next
End Sub

Method 4: Combine sheets with “Professor Excel Tools”

merge sheets, professor excel tools

You like to use the most convenient way? Try the Excel add-in Professor Excel Tools.

  • Just select all the worksheets you’d like to merge,
  • click the button “Merge Sheets” and
  • click on “Start”.

Alternatively, you can further refine your desired settings: Do you want to add the original sheet name in column A? No problem.

Also, define the copy & paste mode as shown in the screenshot on the right-hand side.


Professor Excel Tools Box

This function is included in our Excel Add-In ‘Professor Excel Tools’

(No sign-up, download starts directly)


(New) Method 5: Merge sheets using the Office clipboard

The first method above already dealt with copying and pasting sheets manually. There is one more trick here: Use the Excel clipboard to merge sheets. It’s actually quite simple, just follow these steps.

merge sheets, paste all, clipboard
Steps 1-3: Use the Office clipboard to quickly copy worksheets underneath each other.
  1. Open the clipboard: Click on the small arrow in the right bottom corner of the Clipboard section (on the Home ribbon).
  2. Now you can see the clipboard.
  3. Next, go through each worksheet. Copy all ranges which you later want to merge on one worksheet.
merge sheets, paste all, clipboard
Steps 4-5: Use the “Paste All” button of the clipboard to merge the sheets.
  1. Now, you can see all your copied ranges in the clipboard.
  2. Go to the sheet where you want to paste them underneath each other. Select the first cell.
  3. Click on “Paste all”

That’s it. Especially with larger files, this method could save some time compared to method number 1 above. One small disadvantage: You can further adjust the pasting method, for example using paste special to paste values only.

Henrik Schiffner is a freelance business consultant and software developer. He lives and works in Hamburg, Germany. Besides being an Excel enthusiast he loves photography and sports.

If you’re a Microsoft Excel user, it doesn’t take long before you have many different workbooks full of important spreadsheets. What happens when you need to combine these multiple workbooks together so that all of the sheets are in the same place?

Excel can be challenging at times because it’s so powerful. You know that what you want to do is possible, but you might not know how to accomplish it. In this tutorial, I’ll show you several techniques you can use to merge Excel spreadsheets.

When you need to combine multiple spreadsheets, don’t copy and paste the data from each sheet manually. There are many shortcuts that you can use to save time in combining workbooks, and I’ll show you which one is right for each situation.

Combine Excel SpreadsheetsCombine Excel SpreadsheetsCombine Excel Spreadsheets

Watch & Learn

The screencast below will show you how to combine Excel sheets into a single consolidated workbook. I’ll teach you to use PowerQuery (also called Get & Transform Data) to pull together data from multiple workbooks.

Important: The email addresses used in this tutorial are fictitious (randomly generated) and not intended to represent any real email addresses.

Read on to see written instructions. As always, Excel has multiple ways to accomplish this task, and how you’re working with your data will drive which approach is the best.

1. How to Move & Copy Sheets (Simplest Method)

The easiest method to merge Excel spreadsheets is to simply take the entire sheet and copy it from one workbook to another.

To do this, start off by opening both Excel workbooks. Then, switch to the workbook that you want to copy several sheets from.

Now, hold Control (or Command on Mac) on your keyboard and click on all of the sheets that you want to copy to a separate workbook. You’ll notice that as you do this, the tabs will show as highlighted.

Now, simply right click and choose Move or Copy from the menu.

Move or Copy from MenuMove or Copy from MenuMove or Copy from Menu

Control+click (or command+click) on all of the sheets that you want to move or copy between workbooks, then right click and choose Move or Copy.

On the Move or Copy pop up window, the first thing that you’ll want to do is select the workbook that you want to move the sheets to. Choose the name of the file from the «To book» drop-down.

Move or Copy Popup OptionMove or Copy Popup OptionMove or Copy Popup Option

On the pop-up window, choose the workbook that you want to copy or move your sheets into, and ensure that you check Create a copy if you don’t want to move all of the sheets.

Also, you can choose where the sheets are placed in the new workbook in terms of sequence. The Before sheet menu controls where sequentially in the workbook the sheets will be inserted. You can always choose (move to end) and re-sequence the order the sheets later as needed.

Finally, it’s optional check the box to Create a copy, which will duplicate the sheets and create a separate copy of them in the workbook you’re moving the sheets to. Once you press OK, you’ll see that the sheets we copied are in the combined workbook.

Sheets in Excel workbookSheets in Excel workbookSheets in Excel workbook

Now, the two sheets we selected from a separate workbook are copied into the main workbook.

This approach has a few downsides. If you keep working with two separate files, they aren’t «in sync.» If you make changes to the original workbook that you copied the sheets from, they won’t automatically update in the combined workbook.

2. Prepare to Use Get & Transform Data Tools to Combine Sheets

Excel has an incredibly powerful set of tools that are often called PowerQuery. Beginning with Excel 2016, this feature set was rebranded as Get & Transform Data. 

As the name suggests, these are a set of tools that helps you pull data together from other workbooks and consolidate it into one workbook.

Data Get and Transform Excel ribbonData Get and Transform Excel ribbonData Get and Transform Excel ribbon

In Excel 2016 for Windows or the Office365 version of Excel, you’ll find this feature on the Data tab in the Get & Transform options.

Also, this feature is exclusive to Excel for Windows. You won’t find it in the Mac versions or in the web browser edition of Microsoft’s app.

Before You Start: Check the Data

The most important part of this process is checking your data before you start combining it. The files need to have the same setup for the data structure, with the same columns. You can’t easily combine a four-column spreadsheet and a five-column spreadsheet, as Excel won’t know where to place the data.

Compare data setsCompare data setsCompare data sets

Before you try to combine data with Get & Transform Data feature, it really helps to ensure that the data is in the same structure, with the same columns in each workbook you’re combining.

Often, you’ll find yourself needing to combine spreadsheets when you’re downloading data from systems. In that case, it’s much easier to make sure the system you’re downloading data is configured to download data in the same columns each time.

Before I download data from a service like Google Analytics, I always make sure that I’m downloading the same report format each time. This ensures that I can easily work with and combine multiple spreadsheets together.

Whether you’re pulling data from a system like Google Analytics, MailChimp, or an ERP like SAP or Oracle that powers huge companies, the best way to save time is to ensure that you’re downloading data in a common format.

Now that we’ve checked our data, it’s time to dive into learning how to combine Excel sheets. 

3. How to Combine Excel Sheets in a Folder Full of Files

A few times, I’ve had a folder full of files that I needed to put together into a single, consolidated file. When you’ve got dozens or even hundreds of files, opening them one-by-one to combine them just isn’t feasible. Learning this technique can save you dozens of hours on a single project.

Again, it’s crucial that the data is in the same format. To get started, it helps to place all of the files in the same folder so that Excel can easily watch this folder for changes. 

Combining Folder of filesCombining Folder of filesCombining Folder of files

Make sure that you’ve placed all of your Excel files in the same folder, then choose New Query > From File > From Folder on Excel’s ribbon.

Step 1. Point Excel to the Folder of Files

On the pop-up window, you’ll want to specify a path to the folder that holds your Excel workbooks.

Folder Path Microsoft ExcelFolder Path Microsoft ExcelFolder Path Microsoft Excel

Set the folder path to the folder with the files you want to combine.

You can browse to that path, or simply paste in the path to the folder with your workbooks.

Step 2. Confirm the List of Files

After you show Excel where the workbooks are stored, a new window will pop up that shows the list of files you’re set to combine. Right now, you’re only seeing metadata about the files, and not the data inside of it.

List of files to combineList of files to combineList of files to combine

This window simply shows the files that are going to be combined with our query, 

This window simply shows the files that are going to be combined with our query. You’ll see the file name, the type, and the dates accessed and modified. If you’re missing a file in this list, confirm that all of the files are in the folder and retry the process.

To move on to the next step, click on Edit. 

Step 3. Confirm the Combination

The next menu helps to confirm the data inside your files. Since we’ve already checked that data is the same structure in our multiple files, we can simply click OK on this step.

Confirm Combining Files ExcelConfirm Combining Files ExcelConfirm Combining Files Excel

This is a check-step to ensure that our files are in the same structure, so simply press OK to move to the next step.

Step 4. How to Combine Excel Sheets With a Click

Now, a new window pops up with the list of files we’re set to combine.

At this stage, you’re still seeing metadata about the files and now the data itself. To solve that, click on the double drop-down arrow in the upper right corner of the first column.

Click to Combine FilesClick to Combine FilesClick to Combine Files

Click on the double drop-down arrow in the first column to load the source data from each file.

Voila! Now, you’ll see the actual data from inside the files combined into one place. 

Query Editor Data CombinedQuery Editor Data CombinedQuery Editor Data Combined

Once you combine your data, you’ll see all of it combined into one file, and the original filename shows in the first column.

Scroll through the data to confirm that all of your rows are there. Notice that the only change from your original data is that the filename of each source file is in the first column.

Step 5. Close and Load the Data

Believe it or not, we’re basically finished with combining our Excel spreadsheets. The data is in the Query Editor for now, so we’ll need to «send it back» to regular Excel so that we can work with it.

Click on Close & Load in the upper right corner. You’ll see the finished data in a regular Excel spreadsheet, ready to review and work with.

Combined Data Set in ExcelCombined Data Set in ExcelCombined Data Set in Excel

Once you click Close & Load, you’ll see all of the data from the original files combined into one sheet.

Imagine using this feature to roll up multiple files from different members of your team. Choose a folder that you’ll each store files in, and then combine them into one cohesive file with this feature in just a few minutes.

Recap & Keep Learning

In this tutorial, you learned several techniques for how to combine Excel sheets. When you’ve got many sheets that you need to stitch together, using one of these approaches will save you time so that you can get back to the task at hand!

Check out some of the other tutorials to level up your Excel skills. Each of these tutorials will teach you a method for accomplishing tasks in less time in Microsoft Excel.

How do you merge Excel workbooks? Let me know in the comments section below whether you’ve got a preference for these methods, or a technique of your own that you use.

Did you find this post useful?

Andrew Childress

I believe that life is too short to do just one thing. In college, I studied Accounting and Finance but continue to scratch my creative itch with my work for Envato Tuts+ and other clients. By day, I enjoy my career in corporate finance, using data and analysis to make decisions.

I cover a variety of topics for Tuts+, including photo editing software like Adobe Lightroom, PowerPoint, Keynote, and more. What I enjoy most is teaching people to use software to solve everyday problems, excel in their career, and complete work efficiently. Feel free to reach out to me on my website.

Learn everything about how to merge sheets in Excel, plus how to combine multiple Excel files into one.

using Microsoft Excel on a laptop

Sometimes, the Microsoft Excel data you need is split across multiple sheets or even multiple files. It can be significantly more convenient to have all of this information in the same document.

You can copy and paste the cells you need in a pinch, placing them all on the same sheet. However, depending on how much data you’re working with, this might take a lot of time and effort.

Instead, we’ve rounded up some smarter ways to accomplish the same task. These methods will allow you to quickly and easily merge sheets or files in Excel.

How to Combine Excel Sheets Into One File

If you have multiple Excel files, perhaps each containing numerous sheets, that you want to combine into a single file, you can do this with the Move or Copy Sheet command. This method of merging Excel sheets has its limitations, but it’s quick and straightforward.

First, open up the sheets you want to merge into the same workbook. From there:

  1. From the top ribbon, select the Home tab.
  2. Within the Cells group, click Format.
  3. Select Move or Copy Sheet.

excel move or copy sheet

This opens the Move or Copy window. The To book dropdown lets you select the master spreadsheet where you want to send all of your individual sheets. Select (new book) to create a new file, or select an existing file. Use the Before sheet box to specify the order that the sheets are in (this will be blank if you’re using a new book). When ready, click OK.

Repeat this process for all the sheets that you wish to merge. To save time, you can select multiple sheets in a file by holding Ctrl as you click their tabs at the bottom.

Once done, save your new master document.

For the reverse of this, we’ve also covered how to split a large CSV into separate files.

How to Combine Excel Sheets Into One File With VBA

Rather than performing the above combination technique manually, the quicker way is to use a VBA macro. This will come in especially handy if you perform this task regularly.

First, make sure that all the files you want to combine are in the same folder on your computer. Then, create a new Excel spreadsheet that will bring them all together.

Head to the Developer tab. Within the Code section, select Visual Basic. Click Insert > Module.

For this process, we consulted ExtendOffice. Copy and paste the following code:

 Sub GetSheets()
Path = "C:FILE PATH"
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

Make sure to change the path on the second line to wherever the files are stored on your computer.

Next, click the run button (or press F5) to execute the macro. This will immediately combine all the Excel sheets into your current file. Close the Visual Basic window to return to your spreadsheet and see the result. Don’t forget to save the changes.

How to Merge Excel Data Into One Sheet

Sometimes, you might want to take more than one dataset and present it as a single sheet. This is pretty easy to accomplish in Excel, so long as you take the time to ensure that your Excel data is organized and formatted properly ahead of time.

There are two important conditions for this process to work correctly. First, the sheets you’re consolidating need to use the same layout, with identical headers and data types. Second, there can’t be any blank rows or columns.

When you’ve arranged your data to those specifications, create a new worksheet. It’s possible to run the consolidation procedure in an existing sheet where there’s already data, but it’s easier not to.

excel consolidate

  1. In this new sheet, select the upper-left cell of where you want to place the consolidated data.
  2. Select the Data tab.
  3. Within the Data Tools section, click Consolidate.
  4. On the Function dropdown, select your desired summary function. The default is Sum, which adds values together.
  5. Click the up arrow button in the Reference field. If the data is in another file, use the Browse button.
    1. Highlight the range you wish to consolidate.
    2. Click Add to add the range to All references.
  6. Repeat step five until you’ve selected all the data that you want to consolidate.
  7. Check Create links to source data if you’re going to continue to update the data in other sheets and want this new sheet to reflect that. You can also select which labels are carried across with the Use labels in checkboxes.
  8. Finally, click OK.

Take Caution Before Merging Excel Data

Merging sheets and files in Excel can be complicated and messy. This illuminates one of the most important lessons about Microsoft Excel: it’s always good to plan ahead.

Merging different data sets after the fact is always going to cause a few headaches, especially if you’re working with large spreadsheets that have been in use for a long time. When you start working with a new workbook, it’s best to consider all possibilities of how you will use the file further down the line.

Skip to content

6 примеров — как консолидировать данные и объединить листы Excel в один

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

  • объединить все данные с выбранных листов,
  • объединить несколько листов с различным порядком столбцов,
  • объединить определённые столбцы с нескольких листов,
  • объединить две таблицы Excel в одну по ключевым столбцам.

Сегодня мы займемся проблемой, с которой ежедневно сталкиваются многие пользователи Excel, — как объединить листы Excel в один без использования операций копирования и вставки. Рассмотрим два наиболее распространенных сценария: объединение числовых данных (сумма, количество, среднее и т. д.) и объединение листов ( то есть копирование данных из нескольких листов в один).

Вот что мы рассмотрим в этой статье:

  • Объединение при помощи стандартного инструмента консолидации.
  • Как копировать несколько листов Excel в один.
  • Как объединить листы с различным порядком столбцов.
  • Объединение только определённых столбцов из нескольких листов
  • Слияние листов в Excel с использованием VBA
  • Как объединить два листа в один по ключевым столбцам

Консолидация данных из нескольких листов на одном.

Самый быстрый способ консолидировать данные в Excel (в одной или нескольких книгах) — использовать встроенную функцию Excel Консолидация.

Рассмотрим следующий пример. Предположим, у вас есть несколько отчетов из региональных офисов вашей компании, и вы хотите объединить эти цифры в основной рабочий лист, чтобы у вас был один сводный отчет с итогами продаж по всем товарам.

Как вы видите на скриншоте ниже, четыре объединяемых листа имеют схожую структуру данных, но разное количество строк и столбцов:

Чтобы объединить всю эту информацию на одном листе, выполните следующие действия:

  1. Правильно расположите исходные данные. Чтобы функция консолидации Excel работала правильно, убедитесь, что:
    • Каждый диапазон (набор данных), который вы хотите объединить, находится на отдельном листе. Не помещайте данные на лист, куда вы планируете выводить консолидированные данные.
    • Каждый лист имеет одинаковый макет, и каждый столбец имеет заголовок и содержит похожие данные.
    • Ни в одном списке нет пустых строк или столбцов.
  2. Запустите инструмент «Консолидация». На новом листе, где вы планируете поместить результаты, щелкните верхнюю левую ячейку, начиная с которой должны отображаться консолидированные данные, затем на ленте перейдите на вкладку «Данные» и нажмите кнопку «Консолидация».

Совет. Желательно объединить данные в пустой лист. Если на вашем основном листе уже есть данные, убедитесь, что имеется достаточно места (пустые строки и столбцы) для записи результатов.

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

Если один или несколько листов находятся в другой книге, используйте кнопку «Обзор», чтобы найти эту книгу и использовать ее.

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

Если вы развернете какую-либо группу (щелкнув значок плюса), а затем установите курсор на ячейку с определенным значением, в строке формул отобразится ссылка на исходные данные.
Если флажок не устанавливать, то вы получаете просто таблицу с итоговыми цифрами без всяких формул и ссылок:

Как видите, функция консолидации Excel очень полезна для сбора данных. Однако у нее есть несколько ограничений. В частности, он работает только для числовых значений и всегда обрабатывает эти числа тем или иным образом (сумма, количество, среднее и т. д.). Исходные цифры вы здесь не увидите.

Если вы хотите объединить листы в Excel, просто скопировав и объединив их содержимое, вариант консолидации не подходит. Чтобы объединить всего парочку из них, создав как бы единый массив данных, то вам из стандартных возможностей Excel не подойдёт ничего, кроме старого доброго копирования / вставки. 

Но если вам предстоит таким образом обработать десятки листов, ошибки при этом будут практически неизбежны. Да и затраты времени весьма значительны.

Поэтому для подобных задач рекомендую использовать один из перечисленных далее нестандартных методов для автоматизации слияния.

Как скопировать несколько листов Excel в один.

Как мы уже убедились, встроенная функция консолидации умеет суммировать данные из разных листов, но не может объединять их путем копирования данных на какой-то итоговый лист. Для этого вы можете использовать один из инструментов слияния и комбинирования, включенных в надстройку Ultimate Suite для Excel.

Для начала давайте будем исходить из следующих условий:

  • Структура таблиц и порядок столбцов на всех листах одинаковы.
  • Количество строк везде разное.
  • Листы могут в будущем добавляться или удаляться.

Итак, у вас есть несколько таблиц, содержащих информацию о различных товарах, и теперь вам нужно объединить эти таблицы в одну итоговую, например так, как на рисунке ниже:

Три простых шага — это все, что нужно, чтобы объединить выбранные листы в один.

1.       Запустите мастер копирования листов.

На ленте перейдите на вкладку AblebitsData, нажмите «Копировать листы (Copy Sheets)» и выберите один из следующих вариантов:

  1. Скопировать листы из каждой книги на один лист и поместить полученные листы в одну книгу.
  2. Объединить листы с одинаковыми названиями в один.
  3. Скопировать выбранные в одну книгу.
  4. Объединить данные из выбранных листов на один лист.

Поскольку мы хотим объединить несколько листов путем копирования их данных, то выбираем последний вариант:

1.       Выберите листы и, при необходимости, диапазоны для объединения.

Мастер копирования листов отображает список всех имеющихся листов во всех открытых книгах. Выберите те из них, которые хотите объединить, и нажмите « Далее».

Если вы не хотите копировать все содержимое определенного рабочего листа, используйте специальный значок, чтобы выбрать нужный диапазон, как показано на скриншоте ниже.

В этом примере мы объединяем первые три листа нашей книги:

Совет. Если рабочие листы, которые вы хотите объединить, находятся в другой книге, которая в данный момент закрыта, нажмите кнопку «Добавить файлы …» , чтобы найти и открыть эту книгу.

2.       Выберите, каким образом произвести объединение.

На этом этапе вы должны настроить дополнительные параметры, чтобы ваша информация была объединена именно так, как вы хотите.

Как вставить :

  1. Вставить все – скопировать все данные (значения и формулы). В большинстве случаев это правильный выбор.
  2. Вставлять только значения – если вы не хотите, чтобы переносились формулы, выберите этот параметр.
  3. Создать ссылки на исходные данные – это добавит формулы, связывающие итоговые ячейки с исходными. Выберите этот параметр, если вы хотите, чтобы результат объединения обновлялся автоматически при изменении исходных файлов. Это работает аналогично параметру «Создать ссылки на исходные данные» в стандартном инструменте консолидации в Excel.

Как расположить :

  1. Разместите скопированные диапазоны один под другим – то есть вертикально.
  2. Расположить скопированные диапазоны рядом – то есть по горизонтали.

Как скопировать :

  • Сохранить форматирование – понятно и очень удобно.
    • Разделить скопированные диапазоны пустой строкой – выберите этот вариант, если вы хотите добавить пустую строку между сведениями, скопированными из разных листов. Так вы сможете отделить их друг от друга, если это необходимо.
    • Скопировать таблицы вместе с их заголовками. Установите этот флажок, если хотите, чтобы заголовки исходных таблиц были включены в итоговый лист.

На скриншоте ниже показаны настройки по умолчанию, которые нам подходят:

Нажмите кнопку «Копировать (Copy)», и у вас будет содержимое трех разных листов, объединенное в один итоговый, как показано в начале этого примера.

Быть может, вы скажете, что подобную операцию можно произвести путем обычного копирования и вставки. Но если у вас будет десяток или более листов и хотя бы несколько сотен строк на каждом из них, то это будет весьма трудоемкой операцией, которая займет довольно много времени. Да и ошибки вполне вероятны. Использование надстройки сэкономит вам много времени и избавит от проблем.

Как объединить листы Excel с различным порядком столбцов.

Когда вы имеете дело с файлами, созданными разными пользователями, порядок столбцов в них часто отличается. Как же их объединить? Будете ли вы копировать вручную или перемещать столбцы, чтобы упорядочить их в каждой книге? Это совсем не выход.

Используем инструмент объединения листов Combine Sheets.

Запускаем надстройку через меню Ablebits Data – Combine Sheets.

Выбираем и отмечаем галочками те листы, данные с которых мы хотим объединить. Затем программа анализирует их и предлагает нам список найденных столбцов с указанием того, сколько раз столбец с подобным названием был обнаружен.

Вы должны указать те столбцы, данные из которых вы хотели бы объединить. Можете выбрать их все, можете – только самые важные.

Затем определяем, как нужно вставить собранные данные: целиком с формулами или только значения, либо сформировать ссылки на источники, чтобы обеспечить постоянное обновление и актуальность информации в случае внесения изменений в исходные таблицы.

Также можно указать, что необходимо сохранить исходное форматирование, если оно уникально в каждой таблице. Так вам, кстати, будет проще определить, откуда появились сведения в общем массиве, какая таблица является их источником.

И данные будут идеально скомпонованы по заголовкам столбцов:

Мы получили своего рода сводную таблицу с необходимой информацией.

Объединение определенных столбцов из нескольких листов.

А вот, как мне кажется, наиболее часто встречающаяся ситуация:

  • у вас действительно большие листы с множеством разных столбцов,
  • столбцы расположены на каждом из них по-разному, в произвольном порядке,
  • необходимо объединить только самые важные из них в итоговую таблицу. 

Запустите мастер объединения листов, как мы это делали в предыдущем примере, укажите нужные, а затем выберите соответствующие столбцы. Да, это так просто!

Все дальнейшие шаги мы уже описывали выше. В результате в итоговую таблицу попадают только данные из выбранных вами столбцов:

Эти примеры продемонстрировали только несколько инструментов слияния данных, но это еще не все! Немного поэкспериментировав, вы увидите, насколько полезны и удобны все функции, включенные в пакет. 

Полнофункциональная ознакомительная версия Ultimate Suite доступна для загрузки в по этой ссылке.

Слияние листов в Excel с помощью кода VBA

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

Для этого на вкладке Разработчик (Developer) нажмите кнопку Visual Basic или воспользуйтесь сочетанием клавиш Alt+F11. В открывшемся окне добавьте новый модуль через меню Insert — Module и скопируйте туда текст вот такого макроса:

Sub CopyDataWithHeaders()
    Dim sh As Worksheet
    Dim DestSh As Worksheet
    Dim Last As Long
    Dim shLast As Long
    Dim CopyRng As Range
    Dim StartRow As Long

    With Application
        .ScreenUpdating = False
        .EnableEvents = False
    End With

    'Delete the sheet "RDBMergeSheet" if it exist
    Application.DisplayAlerts = False
    On Error Resume Next
    ActiveWorkbook.Worksheets("RDBMergeSheet").Delete
    On Error GoTo 0
    Application.DisplayAlerts = True

    'Add a worksheet with the name "RDBMergeSheet"
    Set DestSh = ActiveWorkbook.Worksheets.Add
    DestSh.Name = "RDBMergeSheet"

    'Fill in the start row
    StartRow = 2

    'loop through all worksheets and copy the data to the DestSh
    For Each sh In ActiveWorkbook.Worksheets
        If sh.Name <> DestSh.Name Then

'Copy header row, change the range if you use more columns
If WorksheetFunction.CountA(DestSh.UsedRange) = 0 Then
  sh.Range("A1:Z1").Copy DestSh.Range("A1")
End If

            'Find the last row with data on the DestSh and sh
            Last = LastRow(DestSh)
            shLast = LastRow(sh)

            'If sh is not empty and if the last row >= StartRow copy the CopyRng
            If shLast > 0 And shLast >= StartRow Then

                'Set the range that you want to copy
                Set CopyRng = sh.Range(sh.Rows(StartRow), sh.Rows(shLast))

                'Test if there enough rows in the DestSh to copy all the data
                If Last + CopyRng.Rows.Count > DestSh.Rows.Count Then
                    MsgBox "There are not enough rows in the Destsh"
                    GoTo ExitTheSub
                End If

                'This example copies values/formats, if you only want to copy the
                'values or want to copy everything look below example 1 on this page
                CopyRng.Copy
                With DestSh.Cells(Last + 1, "A")
                    .PasteSpecial xlPasteValues
                    .PasteSpecial xlPasteFormats
                    Application.CutCopyMode = False
                End With

            End If

        End If
    Next

ExitTheSub:

    Application.Goto DestSh.Cells(1)

    'AutoFit the column width in the DestSh sheet
    DestSh.Columns.AutoFit

    With Application
        .ScreenUpdating = True
        .EnableEvents = True
    End With
End Sub

Function LastRow(sh As Worksheet)
    On Error Resume Next
    LastRow = sh.Cells.Find(What:="*", _
                            After:=sh.Range("A1"), _
                            Lookat:=xlPart, _
                            LookIn:=xlFormulas, _
                            SearchOrder:=xlByRows, _
                            SearchDirection:=xlPrevious, _
                            MatchCase:=False).Row
    On Error GoTo 0
End Function


Function LastCol(sh As Worksheet)
    On Error Resume Next
    LastCol = sh.Cells.Find(What:="*", _
                            After:=sh.Range("A1"), _
                            Lookat:=xlPart, _
                            LookIn:=xlFormulas, _
                            SearchOrder:=xlByColumns, _
                            SearchDirection:=xlPrevious, _
                            MatchCase:=False).Column
    On Error GoTo 0
End Function

Имейте в виду, что для правильной работы кода VBA все исходные листы должны иметь одинаковую структуру, одинаковые заголовки столбцов и одинаковый порядок столбцов.

В этой функции выполняется копирование данных со всех листов начиная со строки 2 и до последней строки с данными. Если шапка в ваших таблицах занимает две или более строки, то измените этот код, поставив вместо 2 цифры 3, 4 и т.д.:

    'Fill in the start row
    StartRow = 2

При запуске функция добавит в вашу книгу рабочий лист с именем RDBMergeSheet  и скопирует на него ячейки из каждого листа в книге. Каждый раз, когда вы запускаете макрос, он
сначала удаляет итоговый рабочий лист с именем RDBMergeSheet, если он существует, а затем добавляет новый в книгу. Это гарантирует, что данные всегда будут актуальными после запуска кода. При этом формат объединяемых ячеек также копируется.

Ещё несколько интересных примеров кода VBA для объединения листов вашей рабочей книги вы можете найти по этой ссылке.

Как объединить два листа Excel в один по ключевому столбцу

Если вы ищете быстрый способ сопоставить и объединить данные из двух листов, вы можете либо использовать функцию Excel ВПР, либо воспользоваться мастером объединения таблиц Merge Two Tables. 

Последний представляет собой удобный визуальный инструмент, который позволяет сравнивать две таблицы Excel по общему столбцу (столбцам) и извлекать совпадающие данные из справочной таблицы. На скриншоте ниже показан один из возможных результатов.

Более подробно его работа рассмотрена в этой статье.

Мастер объединения двух таблиц также включен в Ultimate Suite for Excel, как и множество других полезных функций.

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

Быстрое удаление пустых столбцов в Excel В этом руководстве вы узнаете, как можно легко удалить пустые столбцы в Excel с помощью макроса, формулы и даже простым нажатием кнопки. Как бы банально это ни звучало, удаление пустых…
Как быстро объединить несколько файлов Excel Мы рассмотрим три способа объединения файлов Excel в один: путем копирования листов, запуска макроса VBA и использования инструмента «Копировать рабочие листы» из надстройки Ultimate Suite. Намного проще обрабатывать данные в…
Как работать с мастером формул даты и времени Работа со значениями, связанными со временем, требует глубокого понимания того, как функции ДАТА, РАЗНДАТ и ВРЕМЯ работают в Excel. Эта надстройка позволяет быстро выполнять вычисления даты и времени и без особых…
Как найти и выделить уникальные значения в столбце В статье описаны наиболее эффективные способы поиска, фильтрации и выделения уникальных значений в Excel. Ранее мы рассмотрели различные способы подсчета уникальных значений в Excel. Но иногда вам может понадобиться только просмотреть уникальные…
Как получить список уникальных значений В статье описано, как получить список уникальных значений в столбце с помощью формулы и как настроить эту формулу для различных наборов данных. Вы также узнаете, как быстро получить отдельный список с…
6 способов быстро транспонировать таблицу В этой статье показано, как столбец можно превратить в строку в Excel с помощью функции ТРАНСП, специальной вставки, кода VBA или же специального инструмента. Иначе говоря, мы научимся транспонировать таблицу.…
Как объединить две или несколько таблиц в Excel В этом руководстве вы найдете некоторые приемы объединения таблиц Excel путем сопоставления данных в одном или нескольких столбцах. Как часто при анализе в Excel вся необходимая информация собирается на одном…

Понравилась статья? Поделить с друзьями:
  • Merging rows in excel
  • Merging of data in excel
  • Merging from excel to word
  • Merging from access to word
  • Merging files in word