Excel vba copy all sheets to one sheet

Содержание

  1. Метод Sheets.Copy (Excel)
  2. Синтаксис
  3. Параметры
  4. Замечания
  5. Пример
  6. Поддержка и обратная связь
  7. VBA to Append Data from multiple Excel Worksheets into a Single Sheet – By Column
  8. VBA Reference
  9. 120+ Project Management Templates
  10. Append data from multiple Worksheets into a single sheet By Column using VBA:Project Objective
  11. How we are going to develop this project module(The KEY steps):
  12. Step 1: Declaring variables which are using in the entire project.
  13. Step 2: Disable Screen Updating is used to stop screen flickering and Disable Events is used to avoid interrupted dialog boxes / popups.
  14. Step 3: Deleting the ‘Append_Data’ Worksheet if it exists in the Workbook. And Display Alerts is used to stop popups while deleting Worksheet.
  15. Step 4: Adding a new WorkSheet at the end of the Worksheet. Naming as ‘Append_Data’ . And finally it is assigned it to object (DstSht).
  16. Step 5: It is looping through each(or all) WorkSheet in the workbook.
  17. Step 5.1: Finding the last column in the ‘Append_Data’ Worksheet using ‘fn_LastColumn ‘ function.
  18. Step 5.2: Finding Last used row and Last used column in the Input Worksheet and assigning it to the objects LstRow and LstRow .
  19. Step 5.3: Check whether there are enough columns in the ‘Append_Data’ Worksheet. Otherwise it displays message to the user and go to the IfError .
  20. Step 5.4: Copying data from the input Worksheet and appending with destination Worksheet.
  21. Step 6: Enableing Screen Updating and Events at the end of the project.
  22. Final VBA Module Code(Macro):
  23. Function to Find Last Row:
  24. Function to Find Last Column:
  25. Instructions to Execute the Procedure:
  26. VBA to Consolidate data from multiple Excel Worksheets into a Single Sheet – By Row
  27. VBA Reference
  28. 120+ Project Management Templates
  29. Consolidate data from multiple Worksheets into a single sheet By Row using VBA:Project Objective
  30. How we are going to develop this project module(The KEY steps):
  31. Step 1: Declaring variables which are using in the entire project.
  32. Step 2: Disable Screen Updating is used to stop screen flickering and Disable Events is used to avoid interrupted dialog boxes / popups.
  33. Step 3: Deleting the ‘Consolidate_Data’ Worksheet if it exists in the Workbook. And Display Alerts is used to stop popups while deleting Worksheet.
  34. Step 4: Adding a new WorkSheet at the end of the Worksheet. Naming as ‘Consolidate_Data’ . And finally it is assigned it to object (DstSht).
  35. Step 5: It is lLooping through each(or all) WorkSheet in the workbook.
  36. Step 5.1: Finding the last row in the ‘Consolidate_Data’ Worksheet using ‘fn_LastRow ‘ function.
  37. Step 5.2: Finding Last used row and Last used column in the Input Worksheet and assigning it to the objects LstRow and LstRow .
  38. Step 5.3: Check whether there are enough rows in the ‘Consolidate_Data’ Worksheet. Otherwise it displays message to the user and go to the IfError .
  39. Step 5.4: Copying data from the input Worksheet and cocatinating with destination Worksheet.
  40. Step 6: Enableing Screen Updating and Events at the end of the project.
  41. Final VBA Module Code(Macro):
  42. Function to Find Last Row:
  43. Function to Find Last Column:
  44. Instructions to Execute the Procedure:

Метод Sheets.Copy (Excel)

Копирует лист в другое место в книге.

Синтаксис

expression. Копирование (до, после)

выражение: переменная, представляющая объект Sheets.

Параметры

Имя Обязательный или необязательный Тип данных Описание
Before Необязательный Variant Лист, перед которым будет размещен скопированный лист. Невозможно указать параметр Before , если указать After.
After Необязательный Variant Лист, после которого будет размещен скопированный лист. Вы не можете указать After , если укажем значение До.

Замечания

Если не указать значение «До» или «После», Microsoft Excel создает новую книгу, содержащую скопированный лист.

Пример

В этом примере выполняется копирование Sheet1, помещая его после Sheet3.

Поддержка и обратная связь

Есть вопросы или отзывы, касающиеся Office VBA или этой статьи? Руководство по другим способам получения поддержки и отправки отзывов см. в статье Поддержка Office VBA и обратная связь.

Источник

VBA to Append Data from multiple Excel Worksheets into a Single Sheet – By Column

VBA Reference

Effortlessly
Manage Your Projects

120+ Project Management Templates

Seamlessly manage your projects with our powerful & multi-purpose templates for project management.

120+ PM Templates Includes:

50+ Excel Templates

50+ PowerPoint Templates

25+ Word Templates

A Powerful & Multi-purpose Templates for project management. Now seamlessly manage your projects, tasks, meetings, presentations, teams, customers, stakeholders and time. This page describes all the amazing new features and options that come with our premium templates.

Save Up to 85% LIMITED TIME OFFER
All-in-One Pack
120+ Project Management Templates
Essential Pack
50+ Project Management Templates

Excel Pack
50+ Excel PM Templates

PowerPoint Pack
50+ Excel PM Templates
MS Word Pack
25+ Word PM Templates
Ultimate Project Management Template
Ultimate Resource Management Template
Project Portfolio Management Templates

Append data from multiple Worksheets into a single sheet By Column using VBA:Project Objective

VBA to Append the data in multiple Worksheets to a newly created Worksheet in the same workbook at the end of the column. The ranges in all worksheets are Append into the ‘Append_Dat’ Worksheet(final Worksheet) one after another in column wise at the end of the column. If data is not available in the Source Worksheet(i.e Input Worksheet) , data will not be updated in the Append_Data(Final) Worksheet. Following is the step by step detailed explanation to automate this process using VBA.

How we are going to develop this project module(The KEY steps):

To Append all worksheets in the workbook, we have to first create a new worksheet(lets call master sheet) and then loop through each worksheet in the workbook. We have to find the valid data range in each worksheet and Append to the newly created master sheet at the end of the column.

Let me explain the key steps to develop this project. We are going to write a procedure (Append_Data_From_Different_Sheets_Into_Single_Sheet_By_Column) with the below approach.

  • Step 1: Declarations: We will declaring required variables and objects which are using in our procedure.
  • Step 2: Disable the Screen updating and Events: temporarily to avoid screen flickering and events triggering.
  • Step 3: Delete old Master sheet: Before creating new master sheet, we have to check if there is any existing sheet with the same name and delete it.
  • Step 4: Adding new worksheet : Lets add new Master sheet(Append_Data Sheet)to paste the data from other sheets
  • Step 5: Loop through each sheet: Now,let’s loop through each worksheet (let’s call source sheet) and paste in the master sheet
  • Step 5.1: Find Last Available Row: Now we have to find the last available row in the master sheet to paste the data at the end of the column.
  • Step 5.2: Find Last used Row and Last used column: Now we have to find the last row and last column of the source sheet
  • Step 5.3: Check if there is enough data: The information got from the above step will helps to check if the data is available in the source sheet
  • Step 5.4: Copy the data if exist: Now, copy the data from source sheet and Append to the master sheet
  • Step 6: Enable the Screen updating and Events: Let’s reset the screen updating and events.

Note: We will be creating two user defined functions which we will be using in the steps 5 to find last row and last columns.

Now, let us see the code for each step:

Step 1: Declaring variables which are using in the entire project.

Step 2: Disable Screen Updating is used to stop screen flickering and Disable Events is used to avoid interrupted dialog boxes / popups.

Step 3: Deleting the ‘Append_Data’ Worksheet if it exists in the Workbook. And Display Alerts is used to stop popups while deleting Worksheet.

Step 4: Adding a new WorkSheet at the end of the Worksheet. Naming as ‘Append_Data’ . And finally it is assigned it to object (DstSht).

Step 5: It is looping through each(or all) WorkSheet in the workbook.

And if statement is checking the Input sheet(Input Data) and destination sheet(Append_Data Sheet) is equal or not. If it is equal, then it is going to check next worksheet. If it is not equal to then it copies the input data and Append to Append_Data Worksheet.

Step 5.1: Finding the last column in the ‘Append_Data’ Worksheet using ‘fn_LastColumn ‘ function.

Step 5.2: Finding Last used row and Last used column in the Input Worksheet and assigning it to the objects LstRow and LstRow .

Finding Last used cell address in the Worksheet and assigned it to object EnRange . Finally finding Input data range in the Input Worksheet and assigning it to the ‘SrcRng ‘ object.

Step 5.3: Check whether there are enough columns in the ‘Append_Data’ Worksheet. Otherwise it displays message to the user and go to the IfError .

Step 5.4: Copying data from the input Worksheet and appending with destination Worksheet.

Step 6: Enableing Screen Updating and Events at the end of the project.

Final VBA Module Code(Macro):

Please find the following macro to Append data from different Worksheets from the Workbook at the end of the column.

Below are the two user defined functions which we have created to find the last row and last column of the given worksheet. We have called these functions in the above procedure at step 5.1 and 5.2.

Function to Find Last Row:

The following function will find the last row of the given worksheet. ‘fn_LastRow’ will accept a worksheet(Sht) as input and give the last row as output.

Function to Find Last Column:

The following function will find the last column of the given worksheet. ‘fn_LastColumn’ will accept a worksheet(Sht) as input and give the last column as output.

Instructions to Execute the Procedure:

You can download the below file and see the code and execute it. Or else, you create new workbook and use the above code and test it. Here are the instructions to use above code.

  1. Open VBA Editor window or Press Alt+F11.
  2. Insert a new module from the Insert menu.
  3. Copy the above procedure and functions and paste it in the newly created module.
  4. You can enter some sample data in multiple sheets. and run the procedure.

Источник

VBA to Consolidate data from multiple Excel Worksheets into a Single Sheet – By Row

VBA Reference

Effortlessly
Manage Your Projects

120+ Project Management Templates

Seamlessly manage your projects with our powerful & multi-purpose templates for project management.

120+ PM Templates Includes:

50+ Excel Templates

50+ PowerPoint Templates

25+ Word Templates

A Powerful & Multi-purpose Templates for project management. Now seamlessly manage your projects, tasks, meetings, presentations, teams, customers, stakeholders and time. This page describes all the amazing new features and options that come with our premium templates.

Save Up to 85% LIMITED TIME OFFER
All-in-One Pack
120+ Project Management Templates
Essential Pack
50+ Project Management Templates

Excel Pack
50+ Excel PM Templates

PowerPoint Pack
50+ Excel PM Templates
MS Word Pack
25+ Word PM Templates
Ultimate Project Management Template
Ultimate Resource Management Template
Project Portfolio Management Templates

Consolidate data from multiple Worksheets into a single sheet By Row using VBA:Project Objective

VBA to concatenate the data in multiple Worksheets to a newly created Worksheet in the same workbook. The ranges in all worksheets are concatenated into the consolidated Worksheet(final Worksheet) one after another in rows wise. If data is not available in the Source Worksheet(i.e Input Worksheet) , data will not be updated in the consolidated Worksheet. Following is the step by step detailed explanation to automate this process using VBA..

How we are going to develop this project module(The KEY steps):

To consolidate all worksheets in the workbook, we have to first create a new worksheet(lets call master sheet) and then loop through each worksheet in the workbook. We have to find the valid data range in each worksheet and append to the newly created master sheet at the end of the row.

Let me explain the key steps to develop this project. We are going to write a procedure (Consolidate_Data_From_Different_Sheets_Into_Single_Sheet) with the below approach.

  • Step 1: Declarations: We will declaring required variables and objects which are using in the our procedure.
  • Step 2: Disable the Screen updating and Events: temporarily to avoid screen flickering and events triggering.
  • Step 3: Delete old Master sheet: Before creating new master sheet, we have to check if there is any existing sheet with the same name and delete it.
  • Step 4: Adding new worksheet : Lets add new Master sheet to paste the data from other sheets
  • Step 5: Loop through each sheet: Now,let’s loop through each worksheet (let’s call source sheet) and paste in the master sheet
  • Step 5.1: Find Last Available Row: Now we have to find the last available row in the master sheet to paste the data
  • Step 5.2: Find Last used Row and Last used column: Now we have to find the last row and column of the source sheet
  • Step 5.3: Check if there is enough data: The information got from the above step will helps to check if the data is available in the source sheet
  • Step 5.4: Copy the data if exist: Now, copy the data from source sheet and append to the master sheet
  • Step 6: Enable the Screen updating and Events: Let’s reset the screen updating and events.

Note: We will be creating two user defined functions which we will be using In the steps 5 to find last row and last columns.

Now, let us see the code for each step:

Step 1: Declaring variables which are using in the entire project.

Step 2: Disable Screen Updating is used to stop screen flickering and Disable Events is used to avoid interrupted dialog boxes / popups.

Step 3: Deleting the ‘Consolidate_Data’ Worksheet if it exists in the Workbook. And Display Alerts is used to stop popups while deleting Worksheet.

Step 4: Adding a new WorkSheet at the end of the Worksheet. Naming as ‘Consolidate_Data’ . And finally it is assigned it to object (DstSht).

Step 5: It is lLooping through each(or all) WorkSheet in the workbook.

And if statement is checking the Input sheet(Input Data) and destination sheet(Consolidated Sheet) is equal or not. If it is equal then it is going to check next worksheet. If it is not equal to then it copies the input data and concatenate to Consolidated Worksheet.

Step 5.1: Finding the last row in the ‘Consolidate_Data’ Worksheet using ‘fn_LastRow ‘ function.

Step 5.2: Finding Last used row and Last used column in the Input Worksheet and assigning it to the objects LstRow and LstRow .

Finding Last used cell address in the Worksheet and assigned it to object EnRange . Finally finding Input data range in the Input Worksheet and assigning it to the ‘SrcRng ‘ object.

Step 5.3: Check whether there are enough rows in the ‘Consolidate_Data’ Worksheet. Otherwise it displays message to the user and go to the IfError .

Step 5.4: Copying data from the input Worksheet and cocatinating with destination Worksheet.

Step 6: Enableing Screen Updating and Events at the end of the project.

Final VBA Module Code(Macro):

Please find the following macro to Consolidate data from different Worksheets from the Workbook.

Below are the two user defined functions which we have created to find the last row and last column of the given worksheet. We have called these functions in the above procedure at step 5.1 and 5.2.

Function to Find Last Row:

The following function will find the last row of the given worksheet. ‘fn_LastRow’ will accept a worksheet(Sht) as input and give the last row as output.

Function to Find Last Column:

The following function will find the last column of the given worksheet. ‘fn_LastColumn’ will accept a worksheet(Sht) as input and give the last column as output.

Final Module:
Let’s

Instructions to Execute the Procedure:

You can download the below file and see the code and execute it. Or else, you create new workbook and use the above code and test it. Here are the instructions to use above code.

  1. Open VBA Editor window or Press Alt+F11.
  2. Insert a new module from the Insert menu.
  3. Copy the above procedure and functions and paste it in the newly created module.
  4. You can enter some sample data in multiple sheets. and run the procedure.

Источник

Sometimes we want to merge multiple sheets into one sheet so that we can easily analyse the data and turn it into some useful information. This articles will tell you how to merge multiple worksheets into one worksheet using VBA.
Example:
008
Here I have fetched some data from server that returns data into different worksheets. I have added one more sheet and named it as “Master”. Other sheet names doesn’t matter.
Now run this macro.

Sub Merge_Sheets()

Dim startRow, startCol, lastRow, lastCol As Long
Dim headers As Range

'Set Master sheet for consolidation
Set mtr = Worksheets("Master")

Set wb = ThisWorkbook
'Get Headers
Set headers = Application.InputBox("Select the Headers", Type:=8)

'Copy Headers into master
headers.Copy mtr.Range("A1")
startRow = headers.Row + 1
startCol = headers.Column

Debug.Print startRow, startCol
'loop through all sheets
For Each ws In wb.Worksheets
     'except the master sheet from looping
     If ws.Name <> "Master" Then
        ws.Activate
        lastRow = Cells(Rows.Count, startCol).End(xlUp).Row
        lastCol = Cells(startRow, Columns.Count).End(xlToLeft).Column
        'get data from each worksheet and copy it into Master sheet
        Range(Cells(startRow, startCol), Cells(lastRow, lastCol)).Copy _
        mtr.Range("A" & mtr.Cells(Rows.Count, 1).End(xlUp).Row + 1)
           End If
Next ws

Worksheets("Master").Activate

End Sub

How to merge sheets using this VBA Macro?

  1. Insert a new sheet and name it “Master” in the workbook. Rename it later if you want.
  2. Insert a module in VBA editor and copy above VBA code.
  3. 009

  4. Run the macro.
  5. You will be asked to select headings. Select the heading and hit OK.

And it is done. All the sheets are merged in master.
0012
How it works?
I assume that you know the basics of object and variable creation in VBA. in the first part we have created object and variables that we will need in our operations.

Well most of the things I have explained using comments in vba code. Let’s look at the main part of this vba code.

For Each ws In wb.Worksheets
     'except the master sheet from looping
     If ws.Name <> "Master" Then
        ws.Activate
        lastRow = Cells(Rows.Count, startCol).End(xlUp).Row
        lastCol = Cells(startRow, Columns.Count).End(xlToLeft).Column
        'get data from each worksheet and copy it into Master sheet
        Range(Cells(startRow, startCol), Cells(lastRow, lastCol)).Copy _
        mtr.Range("A" & mtr.Cells(Rows.Count, 1).End(xlUp).Row + 1)
           End If
Next ws

In earlier articles we learned how to loop through sheets and how to get last row and column using vba.

Here we are looping through each sheet in main workbook using for loop.
For Each ws In wb.Worksheets

Then we exclude “master” sheet from looping, since we will be consolidating our data in that sheet.

Then we get last row and last column number.

Now next line is very important. We have done multiple operations into one line.
Range(Cells(startRow, startCol), Cells(lastRow, lastCol)).Copy _
mtr.Range(«A» & mtr.Cells(Rows.Count, 1).End(xlUp).Row + 1)

First we form a range using startRow, startCol and lastRow and lastCol.

Range(Cells(startRow, startCol), Cells(lastRow, lastCol))
We have copied it using copy method of range.
Range(Cells(startRow, startCol), Cells(lastRow, lastCol)).Copy
We pasted it directly into first blank cell after last non blank cell in column A of master sheet (mtr.Cells(Rows.Count, 1).End(xlUp).Row + 1).

Range(Cells(startRow, startCol), Cells(lastRow, lastCol)).Copy _
        mtr.Range("A" & mtr.Cells(Rows.Count, 1).End(xlUp).Row + 1)

This loops runs for all the sheets and copies each sheets data into master sheet.

Finally, in the end of the macro we activate the mastersheet to see the output.

So yeah guys, this is how you can merge every sheet in a workbook. Let me know if you have any query regarding this VBA code or any excel topic in the comments section below.

 
Download file:

 
Related Articles:

How to loop through sheets

how to get last row and column using vba

Delete sheets without confirmation prompts using VBA in Microsoft Excel

Add And Save New Workbook Using VBA In Microsoft Excel 2016

Display A Message On The Excel VBA Status Bar

Turn Off Warning Messages Using VBA In Microsoft Excel 2016

Popular Articles:

The VLOOKUP Function in Excel

COUNTIF in Excel 2016

How to Use SUMIF Function in Excel

Merging data from more than one Excel sheet in the same workbook is a real hassle… until you use VBA macros.

Macbook with a diary next to it

Excel VBA is an integral part of Excel automation, and VBA’s usage and benefits can’t be undermined. If you’re in an uphill battle trying to consolidate multiple sheets and workbooks in Excel, we’re here to help.

The macros mentioned in this guide will help you achieve the seemingly insurmountable task in a matter of seconds (or minutes, if the data assets are large).

By following this tutorial, you’ll create your own VBA macro in Excel and efficiently merge multiple sheets into one single sheet.

Merging Multiple Excel Sheets in the Same Workbook

For this task, the data is stored in the following sheets:

  • Sheet1
  • Sheet2
  • Sheet3

The sheet names listed above are for illustration purposes only. This VBA macro is generic and doesn’t depend on the sheet names; you can customize the code to use it with any sheet name(s).

Pre-Requisites for Running the Code

There are some prerequisites for running the VBA code listed below.

You need to store the macro code in a new Excel file. Save this workbook with a .xlsm extension. You can save the VBA macro workbook with any name.

Open a new Excel file; press Alt + F11 on your keyboard to open the Excel VBA editor. Once the editor opens, add a new code module by clicking on the Insert tab at the top. Select Module to insert a new module; this is where you’ll be entering the VBA macro code given below.

Excel VBA editor window interface

The data sheets to be consolidated should be in another separate workbook altogether. The name of the workbook and sheets can be whatever you choose.

As soon as you execute the VBA code, the VBA macro will cycle through each available worksheet in the primary workbook (data workbook) and paste the contents into a newly added sheet within the same workbook.

The consolidated data will be available in the sheet named Consolidated.

Running the VBA Code

It’s time to run the newly saved macro code. Copy-paste this code into the VBA editor’s module:

 Sub consolidate_shts()

'declare the various variables used within the code and the vba data types

Dim sht As Worksheet, sht1 As Worksheet, lastrow As Integer, lastrow1 As Integer

'disable screen flickering and alert pop-ups during the execution

With Application

.ScreenUpdating = False

.DisplayAlerts = False

End With

'store the name of the primary workbook in the a macro variable. Replace Test.xlsx with the name of your primary workbook

Set wbk1 = Workbooks("Test.xlsx")

'activate the workbook before performing the function(s) on it

wbk1.Activate

'run a vba for loop to check if a sheet Consolidated already exists. If it exists, the for loop will delete it.

For Each sht In wbk1.Sheets

If sht.Name = "Consolidated" Then sht.Delete

Next sht
'Add a new sheet to store the newly consolidated data

Worksheets.Add.Name = "Consolidated"

'Add some headers to each individual column within the consolidated sheet

With Sheets("Consolidated")

.Range("a1").Value = "OrderDate"

.Range("b1").Value = "Region"

.Range("c1").Value = "Rep"

.Range("d1").Value = "Item"

.Range("e1").Value = "Units"

.Range("f1").Value = "UnitCost"

.Range("g1").Value = "Total"

End With

'The newly created sheet consolidated will hold the consolidated data from each individual sheet in the primary workbook

For i = 1 To wbk1.Worksheets.Count

If Sheets(i).Name <> "Consolidated" Then

'Capture the last populated row from the data sheets in the workbook

lastrow = Sheets(i).Range("a1").End(xlDown).Row

'Capture the last populated row in the Consolidated sheet

lastrow1 = wbk1.Sheets("Consolidated").Range("a1048576").End(xlUp).Row + 1

'Copy data from source sheet and paste it in the consolidated sheet

Sheets(i).Range("a2:g" & lastrow).Copy Destination:=Sheets("Consolidated").Range("a" & lastrow1)

End If

Next i

'Enable Excel VBA functions for future use

With Application

.ScreenUpdating = True

.DisplayAlerts = True

End With

End Sub

The VBA Code Explained

First, declare all the variables you’re using within the code and assign them with the correct VBA data types to make the code run seamlessly.

Once you declare the variables, some basic housekeeping is needed. This is done by disabling screen flickering and suppressing pop-up alerts. For example, when you delete an existing sheet using the VBA code, a prompt within Excel asks for confirmation before deleting the sheet. Prompts like this are suppressed to enhance the speed of execution.

In the next step, you need to define the workbook’s name, which contains all of your data. Replace Test.xlsx with the name and extension of your workbook name. Make sure you surround the name with quotes.

VBA editor interface

Activate the primary workbook and delete any existing sheets with the name Consolidated to eliminate any previously stored data. The VBA code toggles through each sheet, and as soon as it encounters the sheet name Consolidated it’ll delete it. This is done using the VBA IF statement, which checks for logical conditions and deletes the sheet as soon as the condition is met.

A new sheet is added to the primary workbook to store the consolidated data. Subsequently, pre-formatted, standardized headers are added to this sheet. You can change the values of the titles (column headers) by updating the information next to the cell references within quotes.

For example: .Range(“a1”) = “OrderDate” can be replaced with .Range(“a1”) = “OrderNumber”

VBA editor interface

Next, a VBA FOR loop toggles through each worksheet, copies the sheet’s contents, and pastes the contents into the Consolidated worksheet before moving to the next sheet in the workbook. This process repeats until all sheets are copied over.

During this process, all the rows are auto-calculated and pasted in the Consolidated sheet. The last populated row is auto-calculated before the data is pasted in. The macro is dynamic and can adjust to varying data rows within each worksheet.

Once data from all sheets is pasted into the main consolidation sheet, the macro moves to the final leg of the code. The VBA functions initially disabled are enabled again for future use.

VBA editor interface

Consolidating Multiple Sheets Using Excel VBA Macro

Excel VBA is a superfluous programming language, which works well with all Excel components. Each piece of code is essential, and it’s important to remember that the execution is dependent on a line-by-line execution system, so you shouldn’t change the order of the code lines.

To customize the code for your requirements, you can make the required changes and run this code to consolidate the data efficiently and effectively in seconds.

  • #2

Hi Super,
Every day there are tenths of question for consolidation, most of then get unanswered, because the question has been answered many times before.
These kinds of macros do more or less the same thing, only file names, sheets names and ranges change, some time condition like copy rows only if column A has a value of 1.
Here is a VBA from a question yesterday adapted to your ranges, I do not know your file names or sheet names so I improvised, I guessed the Master sheet name is Master

Code:

Sub TranferAllData()
Dim Path As String
Dim FileName As String
Dim Wkb As Workbook
Dim cWkb As Workbook
Dim ws As Worksheet
Dim answer As Integer
Dim lr As Long, lr2 As Long, r As Long
Dim rc As Object

Application.EnableEvents = False
Application.ScreenUpdating = False
Application.DisplayAlerts = False
Application.AskToUpdateLinks = False

answer = MsgBox("Would you like to transfer all data?", vbYesNo + vbQuestion, "Confirmation")

If answer = vbYes Then
Set cWkb = Application.ActiveWorkbook
lr2 = Sheets("Master").Cells(Rows.Count, "A").End(xlUp).Row
    ' Change to the path you will use to idetify the file you wanto to transfer to Master
    Path = "... your path for the files to transfer ..."
    FileName = Dir(Path & "*.xls*", vbNormal)
    Do Until FileName = ""
        Set Wkb = Workbooks.Open(FileName:=Path & FileName)
        For Each ws In Wkb.Worksheets
            For r = 7 To 16 Step 1
                If ws.Range("A" & r).Value <> "" Then
                    ws.Range(Cells(r, 1), Cells(r, 11)).Copy Destination:=cWkb.Sheets("SummaryAccrual").Range("A" & lr2 + 1)
                    lr2 = cWkb.Sheets("SummaryAccrual").Cells(Rows.Count, "A").End(xlUp).Row
                End If
            Next r
        Next ws
        Wkb.Close False
        FileName = Dir()
    Loop
    Application.EnableEvents = True
    Application.ScreenUpdating = True
    Application.DisplayAlerts = True
    Application.AskToUpdateLinks = True
End If
End Sub

Cheers
Sergio

Last edited: Nov 22, 2016

  • #3

Hello Sergio,

Appreciate your help on this however it the code doesn’t work. So I have Sheet1, Sheet2, Sheet3, Sheet4, Sheet5 and Sheet6 and I need to transfer the data in Range A7:K16 of All Sheets to a Sheet name Master. Not All Cell in Range A7:K16 are filled out which means we need to have a VBA Code — Range(«A» & Rows.Count).End(xlUp).Offset(1).Select so that whenever Sheet1 have blank rows Sheet 2 data will be paste in the next blank row in Sheet named Master.In pasting the data in Sheet Master it should start in Row 6

Hi Super,
Every day there are tenths of question for consolidation, most of then get unanswered, because the question has been answered many times before.
These kinds of macros do more or less the same thing, only file names, sheets names and ranges change, some time condition like copy rows only if column A has a value of 1.
Here is a VBA from a question yesterday adapted to your ranges, I do not know your file names or sheet names so I improvised, I guessed the Master sheet name is Master

Code:

Sub TranferAllData()
Dim Path As String
Dim FileName As String
Dim Wkb As Workbook
Dim cWkb As Workbook
Dim ws As Worksheet
Dim answer As Integer
Dim lr As Long, lr2 As Long, r As Long
Dim rc As Object

Application.EnableEvents = False
Application.ScreenUpdating = False
Application.DisplayAlerts = False
Application.AskToUpdateLinks = False

answer = MsgBox("Would you like to transfer all data?", vbYesNo + vbQuestion, "Confirmation")

If answer = vbYes Then
Set cWkb = Application.ActiveWorkbook
lr2 = Sheets("Master").Cells(Rows.Count, "A").End(xlUp).Row
    ' Change to the path you will use to idetify the file you wanto to transfer to Master
    Path = "... your path for the files to transfer ..."
    FileName = Dir(Path & "*.xls*", vbNormal)
    Do Until FileName = ""
        Set Wkb = Workbooks.Open(FileName:=Path & FileName)
        For Each ws In Wkb.Worksheets
            For r = 7 To 16 Step 1
                If ws.Range("A" & r).Value <> "" Then
                    ws.Range(Cells(r, 1), Cells(r, 11)).Copy Destination:=cWkb.Sheets("SummaryAccrual").Range("A" & lr2 + 1)
                    lr2 = cWkb.Sheets("SummaryAccrual").Cells(Rows.Count, "A").End(xlUp).Row
                End If
            Next r
        Next ws
        Wkb.Close False
        FileName = Dir()
    Loop
    Application.EnableEvents = True
    Application.ScreenUpdating = True
    Application.DisplayAlerts = True
    Application.AskToUpdateLinks = True
End If
End Sub

Cheers
Sergio

  • #4

assuming the Master sheet is called «Master», try

Code:

Sub MM1()
Dim ws As Worksheet, lr As Long
lr = Sheets("Master").Cells(Rows.Count, "A").End(xlUp).Row + 1
For Each ws In Worksheets
    If ws.Name <> "Master" Then
        ws.Range("A7:K16").Copy Sheets("Master").Range("A" & lr)
        lr = Sheets("Master").Cells(Rows.Count, "A").End(xlUp).Row + 1
    End If
Next ws
End Sub

  • #5

If empty cells is the problem change the macro
First time you set lr2 use: lr2=1
and second time instead of lr2 = cWkb.Sheets(«SummaryAccrual»).Cells(Rows.Count, «A»).End(xlUp).Row
use lr2=lr2+10
Cheers
Sergio

Last edited: Nov 23, 2016

  • #6

Hello Sergio — Appreciate your help on this but the code is not working I am not sure why :(

Hello Michael,

The Code Work! Eureka! I would like to know if I wanted to paste the data starting Column N, is this the right code? I also wanted to know if the VBA in Columns A — M (the code that you first posted) will be affected if I have another table to VBA in Columns N onward? Thank You!!!!

Code:

Sub MM1()
Dim ws As Worksheet, lr As Long
lr = Sheets("Master").Cells(Rows.Count, "N").End(xlUp).Row + 1
For Each ws In Worksheets
    If ws.Name <> "Master" Then
        ws.Range("A7:K16").Copy Sheets("Master").Range("N" & lr)
        lr = Sheets("Master").Cells(Rows.Count, "N").End(xlUp).Row + 1
    End If
Next ws
End Sub

assuming the Master sheet is called «Master», try

Code:

Sub MM1()
Dim ws As Worksheet, lr As Long
lr = Sheets("Master").Cells(Rows.Count, "A").End(xlUp).Row + 1
For Each ws In Worksheets
    If ws.Name <> "Master" Then
        ws.Range("A7:K16").Copy Sheets("Master").Range("A" & lr)
        lr = Sheets("Master").Cells(Rows.Count, "A").End(xlUp).Row + 1
    End If
Next ws
End Sub

  • #7

One last question, what is the code that I need to add if I wanted to add a condition wherein if the data in Column B is = «No», the entire row will not be included in pasting it to Master sheet and in what part of the code should I add it? I really appreciate all your help I am almost done with my task and that’s because of you guys. Thank You!!!

  • #8

Try this…..UNTESTED

Code:

Sub MM1()
Dim ws As Worksheet, lr As Long, r As Long
lr = Sheets("Master").Cells(Rows.Count, "A").End(xlUp).Row + 1
For Each ws In Worksheets
    If ws.Name <> "Master" Then
     ws.Activate
     For r = 7 To 16
        If Range("B" & r).Value <> "No" Then
        Rows(r).Copy Sheets("Master").Range("A" & lr)
        lr = Sheets("Master").Cells(Rows.Count, "A").End(xlUp).Row + 1
        End If
    Next r
    End If
Next ws
End Sub

  • #9

Hello Michael,

I encounter a debug message when I am trying to run the code. The debug starts in this code Rows(r).CopySheet(«Master»)

I am not sure if it’s because I gave the wrong sequence.

I needed to copy all sheet range A22:L31 in «Master» Column N:Y but the condition is if the row data in Column L of every sheet is «No» it should not be included in the rows that will be paste in the Master sheet.

Sub MM1()
Dim ws As Worksheet, lr As Long, r As Long
lr = Sheets(«Master»).Cells(Rows.Count, «A»).End(xlUp).Row + 1
For Each ws In Worksheets
If ws.Name <> «Master» Then
ws.Activate
For r = 7 To 16
If Range(«B» & r).Value <> «No» Then
Rows(r).Copy Sheets(«Master»).Range(«A» & lr)
lr = Sheets(«Master»).Cells(Rows.Count, «A»).End(xlUp).Row + 1
End If
Next r
End If
Next ws
End Sub

Last edited by a moderator: Nov 26, 2016

  • #10

I’m confused…..
we were copying from columns A to K with the criteria in col B……now it’s A to L with the criteria in L ?????

Can you clearly describe what you REALLY want to do ????

Like this post? Please share to your friends:
  • Excel vba control type
  • Excel vba const array
  • Excel vba commandbar controls
  • Excel vba combobox1 list
  • Excel vba combobox ячейка