Copy rows from one workbook to another if condition is fulfilled - excel

how can I copy/paste rows from one workbook to another if the following conditions are met:
Copy all rows from the source workbook(wb.Source,sheet1) if they are from the actual month(column 8 containing true dates) and paste them to my master workbook(Wb) in sheet 3. Only copy the rows which have the first day of the month as date in column 8.
Example:
Lets say today is the 14.05.2020.
Triggering the macro would copy all rows from the source workbook with the date 01.05.2020(column 8) and paste them to wb in Sheet 3.
So the macro needs to refer to the Today function to able to say which month it actually is right now, and then in the next step to copy the rows which are frim the same month BUT only from the first day of said month.
Would appreciate any help!
Private Sub CommandButton3_Click()
Dim fname As String, wbSource As Workbook, wsSource As Worksheet
fname = Me.TextBox1.Text
If Len(fname) = 0 Then
MsgBox "No file selected", vbCritical, "Error"
Exit Sub
End If
Set wbSource = Workbooks.Open(fname, False, True) ' no link update, read only
Set wsSource = wbSource.Sheets("Sheet1") ' change to suit
Dim wb As Workbook, ws As Worksheet
Set wb = ThisWorkbook
Set ws = wb.Sheets("Table 3")
' Set your source and destination worksheets as objects here
Set wsSource = wbSource.Sheets("Sheet1")
Dim i As Long, destination_row As Long
Dim source_rng As Range, destination_rng As Range
destination_row = 1
For i = 1 To 10 ' See note below regarding for vs while loop for this
' Check dates only against cells that contain date values (in case there is a non-date value in one of the cells)
If VarType(wsSource.Cells(i, 8)) = vbDate Then
' Condition checks that the date is today
If Format(Now, "yyyy/mm/dd") = Format(wsSource.Cells(i, 8).Value2, "yyyy/mm/dd") Then
' Set source and destination ranges
Set source_rng = wsSource.Range(wsSource.Cells(i, 1), wsSource.Cells(i, 10000))
Set destination_rng = ws.Range(ws.Cells(destination_row, 1), destination_sheet.Cells(destination_row, 10000))
source_rng.Copy destination_rng ' Alternatively use destination_rng.Value2 = source_rng.Value2
destination_row = destination_row + 1 ' Iterate the destination row so that the next copy outputs to the next row
End If
End If
Next i
' close source worbook no save
wbSource.Close False
End Sub

The question was a little vague as to the formatting of the worksheets (which columns contain data, where you want to begin printing, if you know how many rows the source data is, if all cells within the data range are populated, etc.), but I've written an example here that can be tweaked to fit the worksheets you're using.
Option Explicit
Sub CopyRows()
' Set your source and destination worksheets as objects here
Dim source_sheet As Worksheet, destination_sheet As Worksheet
Set source_sheet = ActiveWorkbook.Sheets("A")
Set destination_sheet = ActiveWorkbook.Sheets("B")
Dim i As Long, destination_row As Long
Dim source_rng As Range, destination_rng As Range
destination_row = 1
For i = 1 To 10 ' See note below regarding for vs while loop for this
' Check dates only against cells that contain date values (in case there is a non-date value in one of the cells)
If VarType(source_sheet.Cells(i, 8)) = vbDate Then
' Condition checks that the date is today
If Format(Now, "yyyy/mm/dd") = Format(source_sheet.Cells(i, 8).Value2, "yyyy/mm/dd") Then
' Set source and destination ranges
Set source_rng = source_sheet.Range(source_sheet.Cells(i, 1), source_sheet.Cells(i, 10))
Set destination_rng = destination_sheet.Range(destination_sheet.Cells(destination_row, 1), destination_sheet.Cells(destination_row, 10))
source_rng.Copy destination_rng ' Alternatively use destination_rng.Value2 = source_rng.Value2
destination_row = destination_row + 1 ' Iterate the destination row so that the next copy outputs to the next row
End If
End If
Next i
End Sub
I've used sheets "A" and "B" as proxies for your source and destination worksheets. You need to set these objects to your actual source and destination worksheets in your code.
I've also initalized destination_row as 1, assuming you want the copied rows to be printed starting on the first row of the destination worksheet, but this can be set to 2 (if there are headers) or to any row you prefer the output starts on. You may want to add additional code to find the next empty row if you want the new rows to be added underneath whatever data already exists in the worksheet.
The for loop is written as a basic example, assuming that you know how many rows of data there are. If you expect the size of the source range to change (i.e. rows are often added and/or removed), you would want to either determine a final row before starting the loop (by using xlUp/xlDown or similar), or use a while loop instead of a for loop (if there is a column that is always populated that you can use as part of the while condition).
In the section where the source_rng and destination_rng are set, replace the numbers 1 and 10 with the first and last columns of the data (for example, if the data starts on column 3 and finishes on column 15, these should be changed to 3 and 15 respectively).

Related

variable referencing a cell date value not passing to a copy paste filter

I have a spreadsheet that operators input data in, with the A column being the date, and the data is input by row. The A column is a formula that adds +1 to the date in the previous cell, going all the way down recursively to auto-populate the date as the sheet is filled out.
I have to have a report printed out at the end of every day, and I am trying to use VBA to filter the rows out by a date that the operator inputs on another sheet in cell B2. I need the macro to grab that date value, and pass it as a variable to the filter in order to pull the 12 rows of that date and paste it into a new sheet. Unfortunately, the value it pulls is not being passed, and when I put a MsgBox command in there, it shows it's pulling 12:00 AM and not a date. When using the Date variable, it also breaks the filter on the bottom macro below (trying 2 different versions just to get this working).
I'm not good with VBA, so my macros were pulled from example websites and I tailored them to what I need.
This is one macro I have tried:
Sub For_RangeCopy()
Dim rDate As Date
Dim rSheet As Worksheet
Set rSheet = ThisWorkbook.Worksheets("EOS")
rDate = CDate(rSheet.Range("B2").Value)
MsgBox (rDate)
' Get the worksheets
Dim shRead As Worksheet
Set shRead = ThisWorkbook.Worksheets("Bi-Hourly Report")
Dim shWrite As Worksheet
Set shWrite = ThisWorkbook.Worksheets("Report")
' Get the range
Dim rg As Range
Set rg = shRead.Range("A1").CurrentRegion
With shWrite
' Clear the data in output worksheet
.Cells.ClearContents
' Set the cell formats
'.Columns(1).NumberFormat = "dd/mm/yyyy"
'.Columns(3).NumberFormat = "$#,##0;[Red]$#,##0"
'.Columns(4).NumberFormat = "0"
'.Columns(5).NumberFormat = "$#,##0;[Red]$#,##0"
End With
' Read through the data
Dim i As Long, row As Long
row = 1
For i = 1 To rg.Rows.Count
If rg.Cells(i, 1).Value2 = rDate Or i = 1 Then
' Copy using Range.Copy
rg.Rows(i).Copy
shWrite.Range("A" & row).PasteSpecial xlPasteValues
' move to the next output row
row = row + 1
End If
Next i
End Sub
And here is another Macro I have tried to use. This one actually gives me the 3 header rows which I don't need, but I don't mind, this paste is a reference for the report layout anyway, so the operators won't see this sheet. But this macro does give me the first block of the date range: 1/1/2023. I do know that the "rgCriteria As String" is likely incorrect, but that is how I get anything useful from this macro. If I change that rgCriteria to a Date, it breaks the rgData.AdvancedFilter command, and I haven't learned enough VBA to know why. And my boss wants this done today, although here I am posting here, thus it's not getting done today.
Sub AdvancedFilterExample()
' Get the worksheets
Dim rSheet As Worksheet
Set rSheet = ThisWorkbook.Worksheets("EOS")
Dim shRead As Worksheet, shWrite As Worksheet
Set shRead = ThisWorkbook.Worksheets("Bi-Hourly Report")
Set shWrite = ThisWorkbook.Worksheets("Report")
' Clear any existing data
shWrite.Cells.Clear
' Remove the any existing filters
If shRead.FilterMode = True Then
shRead.ShowAllData
End If
' Get the source data range
Dim rgData As Range, rgCriteria As String
Set rgData = shRead.Range("A1").CurrentRegion
' IMPORTANT: Do not have any blank rows in the criteria range
'Set rgCriteria = rSheet.Range("B2")
rgCriteria = rSheet.Range("B2").Value
MsgBox (rgCriteria)
' Apply the filter
rgData.AdvancedFilter Action:=xlFilterCopy, CriteriaRange:=rgCriteria _
, CopyToRange:=shWrite.Range("A1")
End Sub
I don't know which method of filtering and pasting is best for my situation, but I do know that the faster is better. I'm copying entire rows, and it needs to be efficient because this log contains a lot of data. I only need one of these macros to work, but I will be heavily modifying them and chaining them together with about 5 other filter/copy/paste sequences to follow, along with printOut commands after that, and finalized by clearing the sheets it pastes to, and then re-enabling all the functionality of the sheet (calculations, displaystatusbar, events, and screenupdating) all to make it quicker while the macro is running. All of these reports will be run using the macro with a button click.
Any thoughts or suggestions would be greatly appreciated. I've been struggling with this for a couple of weeks now. I'm at a loss and turning to the community that has helped me with a TON of questions over the past 20 or so years just by a Google search!
Other information:
I'm using Office 365 on a Windows 10/11 machine. The headers of the sheet it filters does contain merged cells as the header is rows 1-3, there is a lot of data in this sheet that grows through the year. 12 rows per day for an entire year. These macros are written in a Module aptly named "Module 1" if that helps. I do have this workbook, and the original log saved on OneDrive that can be shared.
When using Advanced Filter your criteria range should have headers which match your data table.
Sub AdvancedFilterExample()
Dim rSheet As Worksheet, shRead As Worksheet, shWrite As Worksheet
Dim rgData As Range, rgCriteria As Range
Set rSheet = ThisWorkbook.Worksheets("EOS")
Set shRead = ThisWorkbook.Worksheets("Bi-Hourly Report")
Set shWrite = ThisWorkbook.Worksheets("Report")
Set rgData = shRead.Range("A1").CurrentRegion 'source data range
'## criteria range needs to include a matching date header...
Set rgCriteria = rSheet.Range("B3:B4") 'eg. "Date" in B3, date value in B4
shWrite.Cells.Clear ' Clear any existing data
If shRead.FilterMode = True Then shRead.ShowAllData ' Remove the any existing filters
rgData.AdvancedFilter Action:=xlFilterCopy, _
CriteriaRange:=rgCriteria, _
CopyToRange:=shWrite.Range("A1")
End Sub

Errors highlighting differences between sheets and copy to new sheet?

In essence, I want to compare two sheets, one containing data from Today, the other from Yesterday, and then copy the lines with changes to a third sheet.
The code I am currently using (seen below) mostly works but has a couple errors (also broken out below) that I want to iron out.
Sub Changed()
set wsa = Sheets("Today")
Set wsb = Sheets("Yesterday")
Set wse = Sheets("Line Changes")
Dim mycell as range
Dim mydiff as integer
For each mycell in wsa.usedrange
If Not mycell.Value = wsb.Cells(mycell.Row, mycell.Column).Value Then
mycell.Interior.Color = RGB(250, 250, 50)
mycell.Range("B").Interior.Color = RGB (250, 250, 50)
mycell.EntireRow.Copy wse.Range("A" & Rows.Count).xlUp).Offset(1)
End If
Next
End Sub
Breakdown of the individual desired functions and issues within the loop:
If Not mycell.Value = wsb.Cells(mycell.Row, mycell.Column).Value Then
Compare Sheets("Today") and Sheets("Yesterday") to find differences. This line works.
mycell.Interior.Color = RGB(250, 250, 50)
Highlight the changed items on Sheets("Today"). This line works.
mycell.Range("B").Interior.Color = RGB (250, 250, 50)
For reference, Column A is just a general reference number which has no real bearing on the rest of the data, but Column B contains an alpha-numeric code specific to the actual items in each line which is why I want to highlight column B instead of A if there are changes.
Highlight Column B in Sheets("Today") if there are changes in the line to allow for easy identification of lines containing changes. The issue I run into with this function is that it doesn't actually work. It doesn't give me an error message so I haven't been able to actually identify what the problem is. This particular function is not 100% necessary so I would be amenable to just removing it.
mycell.EntireRow.Copy wse.Range("A" & Rows.Count).xlUp).Offset(1)
Copy rows with changes from Sheets("Today") and paste it in Sheets("Line Changes"). The issue I run into with this function is it copies changed lines multiple times, once for every individual change.
For example, if Columns D,E,F, and G all have changes, "D" will be highlighted and the row will be copied, then "E" will be highlighted and the row will be copied, and so on. Obviously that's not ideal if there's dozens of lines with 5 or 6 changes each.
My main issue is with that last line, I think the easiest fix would be to remove it from the current loop and add it back in later in the code so it doesn't copy over every individual change but past attempts of mine to remove it broke everything. Its a pretty large document, (1500ish rows, 32 columns) so looping the same data potentially a couple hundred times tends to crash excel. Any suggestions to fix this issue or even streamline the process would be greatly appreciated.
HighLighting Differences: a Row Range Approach
The Code
Option Explicit
Sub Changed()
' Define workbook.
Dim wb As Workbook
Set wb = ThisWorkbook
' Define worksheets.
Dim wsa As Worksheet
Set wsa = wb.Worksheets("Today")
Dim wsb As Worksheet
Set wsb = wb.Worksheets("Yesterday")
Dim wse As Worksheet
Set wse = wb.Worksheets("Line Changes")
' Define Today Used Range.
Dim rng As Range
Set rng = wsa.UsedRange
Dim RowRange As Range
Dim cel As Range
Dim copyRow As Boolean
' Loop through rows of Today Used Range.
For Each RowRange In rng.Rows
' Initialize Copy Row Boolean.
copyRow = False
' Loop through each cell in current row of Today Used Range.
For Each cel In RowRange.Cells
' Ceck value in current cell on Today worksheet against the value
' of the same cell on Yesterday Worksheet.
If Not cel.Value = wsb.Cells(cel.Row, cel.Column).Value Then
' Set Copy Row Boolean to True indicating that this
' row will be copied and the value in "B" column will be
' hightlighted.
copyRow = True
' Highlight current cell in Today Worksheet.
cel.Interior.Color = RGB(250, 250, 50)
End If
Next cel
' If any differences have been found...
If copyRow Then
RowRange.Cells(2).Interior.Color = RGB(250, 250, 50)
RowRange.Copy wse.Range("A" & Rows.Count).End(xlUp).Offset(1)
End If
Next
' Inform user.
MsgBox "Data transferred.", vbInformation, "Success"
End Sub

Add rows before pasting data in a new sheet (between specific cells)

I have a sheet with data and I want to copy its data to another sheet. That's simple, but the problem is, I have to copy that selection to a range between two cells that is set, so if I add another row with data in the first sheet then when the macro runs, the data will overwrite the cells below the limit. How do I make it that if I add a row in the first sheet, before the macro pastes the data in the other sheet another row or a number of rows will be created to avoid the limit below being overwritten?
For example, if the number of rows between two cells is 5 and the range I need to paste is 7, then, prior to pasting the data, the macro creates two more rows.
Thank you
Calculate the difference and add rows if required
Option Explicit
Sub CopyInsert()
Dim rngSource As Range
Set rngSource = Selection ' range to copy from
Const SHEET_TARGET = "Sheet2"
Const RNG_TARGET = "C12:C16"
Dim wb As Workbook, wsTarget As Worksheet
Dim rngTarget As Range, n As Long
Set wb = ThisWorkbook
Set wsTarget = wb.Sheets(SHEET_TARGET)
Set rngTarget = wsTarget.Range(RNG_TARGET)
' insert new ones
n = rngSource.Rows.Count - rngTarget.Rows.Count
If n > 0 Then
rngTarget.Rows("2:" & n + 1).EntireRow.Insert
End If
rngSource.Copy rngTarget.Cells(1, 1)
End Sub

Excel VBA copy row automatically

I need help to create an automatic method to copy a row to a specific sheet.
I have a Tab (Sales) with a WEB api query importing data in this sheet every 5 min. I have a row within the Sales sheet with a name range identifying each item. The row has 100 different names and there are 100 sheets created with same names within the workbook.
I want to copy the entire row for each item and copy it to the sheet with the same name of the item.
This is to fire off the copy sub:
'Copy Sales data Every 10 Min
Sub test()
'Application.OnTime Now + TimeValue("00:10:00"), "my_Procedure…"
End Sub
I have seen many methods on how to copy the row automatically, but I need help in copy row and use the item name and paste to other sheet with same name.
Without further information here is an outline of what i described in the comments. Here the list of named ranges starts at cell J3 in NamesSheet. In the image, i have shown it in the same sheet (SourceSheet for simplicity). The list is read into an array and that array is looped to select the appropriate sheet to set the values in.
Rather than copy and paste it sets the target row (the next available row), in the sheet accessed by the array index, equal to the source row (copyRow). A With statement is used to avoid selecting the target sheet (more efficient).
No error handling added for missing sheets at present.
I haven't assumed there will be a list of 100 named ranges in the sheet, otherwise you could have sized the array from the start.
Named ranges in ColA of Sales tab:
List of named ranges in Names sheet (abbreviated)
Option Explicit
Private Sub myProc()
Dim wb As Workbook
Dim wsSource As Worksheet
Dim wsNames As Worksheet
Set wb = ThisWorkbook
Set wsSource = wb.Worksheets("Sales")
Set wsNames = wb.Worksheets("Names")
Dim namesArr()
namesArr = wsNames.Range("J3:J" & wsNames.Cells(wsNames.Rows.Count, "J").End(xlUp).Row).Value
If UBound(namesArr, 1) <> wsSource.Range("ITEMName").Rows.Count Then
MsgBox "There are not a matching number of named ranges listed in Names sheet."
Exit Sub
End If
Dim i As Long
Dim currLastRow As Long
'Any optimization code could actually go in outer calling sub but consider
'some such as the following
Application.ScreenUpdating = False
Dim copyRow As Range
For i = LBound(namesArr, 1) To UBound(namesArr, 1)
With wb.Worksheets(namesArr(i, 1))
Set copyRow = wsSource.Range(namesArr(i, 1)).EntireRow
If IsEmpty(.Range("A1")) Then 'First row in sheet is available
.Rows(1).Value = copyRow.Value2
Else
currLastRow = .Cells(.Rows.Count, "A").End(xlUp).Row
.Rows(currLastRow + 1).Value = copyRow.Value2
End If
End With
Next i
Application.ScreenUpdating = True
End Sub
Version 2:
Looping Named Ranges in Sales sheet (assumes only 101 Named Ranges in the sheet, tested with workbook scope, and that you will ignore 1 of these which is called ITEMName, no list required in a different sheet. Approach adapted from #user1274820.
Option Explicit
Private Sub myProc2()
Dim wb As Workbook
Dim wsSource As Worksheet
Set wb = ThisWorkbook
Set wsSource = wb.Worksheets("Sales")
Dim currLastRow As Long
'Any optimization code could actually go in outer calling sub but consider
'some such as the following
Application.ScreenUpdating = False
Dim copyRow As Range
Dim nm As Variant
For Each nm In ThisWorkbook.Names
If nm.RefersToRange.Parent.Name = "Sales" And nm.Name <> "ITEMName" Then
With wb.Worksheets(nm.Name)
Set copyRow = wsSource.Range(nm.Name).EntireRow
If IsEmpty(.Range("A1")) Then 'First row in sheet is available
.Rows(1).Value = copyRow.Value2
Else
currLastRow = .Cells(.Rows.Count, "A").End(xlUp).Row
.Rows(currLastRow + 1).Value = copyRow.Value2
End If
End With
End If
Next nm
Application.ScreenUpdating = True
End Sub

Excel: Populate Data Across Multiple Worksheets

Unfortunately for my employer, none of my network engineering courses included advanced Excel formula programming. Needless to say, I know nothing about Excel save for basic SUM and COUNT formula commands.
My employer has an Excel workbook with multiple worksheets within it representing each month of the calendar year. We want to be able to have a "total" worksheet in the workbook that reflects all data across the entire workbook in each column/row.
An example for the sake of clarity:
In the worksheet "May_2013", column A is labeled "DATE". Cell A2 contains the data "MAY-1".
In the worksheet "June_2013", column A is labeled "DATE". Cell A2 contains the data "JUNE-1".
In the worksheet "Total", column A is labeled "DATE". We want cells A2 to reflect "MAY-1" and A3 to reflect "JUNE-1".
We want to do this for all worksheets, columns A-Q, rows 2-33 and populate a master sheet at the very end containing all data in all worksheets in their corresponding columns.
Is this possible?
Here are two VBA solutions. The first does this:
Check if a sheet "totals" exists. Create it if it does not
Copy the first row (A to Q) of first sheet to "totals"
Copy block A2:Q33 to "totals" sheet starting at row 2
Repeat for all other sheets, appending 32 rows lower each time
The second shows how to do some manipulation of the column data before copying: for each column it applies the WorksheetFunction.Sum(), but you could replace that with any other aggregating function that you would like to use. It then copies the result (one row per sheet) to the "totals" sheet.
Both solutions are in the workbook you can download from this site. Run the macros with , and pick the appropriate one from the list of options that shows up. You can edit the code by invoking the VBA editor with .
Sub aggregateRaw()
Dim thisSheet, newSheet As Worksheet
Dim sheetCount As Integer
Dim targetRange As Range
sheetCount = ActiveWorkbook.Sheets.Count
' add a new sheet at the end:
If Not worksheetExists("totals") Then
Set newSheet = ActiveWorkbook.Sheets.Add(after:=Sheets(sheetCount))
newSheet.Name = "totals"
Else
Set newSheet = ActiveWorkbook.Sheets("totals")
End If
Set targetRange = newSheet.[A1]
' if you want to clear the sheet before copying data, uncomment this line:
' newSheet.UsedRange.Delete
' assuming you want to copy the headers, and that they are the same
' on all sheets, you can copy them to the "totals" sheet like this:
ActiveWorkbook.Sheets(1).Range("1:1").Copy targetRange
Set targetRange = targetRange.Offset(1, 0) ' down a row
' copy blocks of data from A2 to Q33 into the "totals" sheet
For Each ws In ActiveWorkbook.Worksheets
If ws.Name <> newSheet.Name Then
ws.Range("A2", "Q33").Copy targetRange
Set targetRange = targetRange.Offset(32, 0) ' down 32 rows
End If
Next ws
End Sub
Sub aggregateTotal()
Dim thisSheet, newSheet As Worksheet
Dim sheetCount As Integer
Dim targetRange As Range
Dim columnToSum As Range
sheetCount = ActiveWorkbook.Sheets.Count
' add a new sheet at the end:
If Not worksheetExists("totals") Then
Set newSheet = ActiveWorkbook.Sheets.Add(after:=Sheets(sheetCount))
newSheet.Name = "totals"
Else
Set newSheet = Sheets("totals")
End If
' assuming you want to copy the headers, and that they are the same
' on all sheets, you can copy them to the "totals" sheet like this:
Set targetRange = newSheet.[A1]
ActiveWorkbook.Sheets(1).Range("A1:Q1").Copy targetRange
Set targetRange = targetRange.Offset(1, 0) ' down a row
For Each ws In ActiveWorkbook.Worksheets
' don't copy data from "total" sheet to "total" sheet...
If ws.Name <> newSheet.Name Then
' copy the month label
ws.[A2].Copy targetRange
' get the sum of the coluns:
Set columnToSum = ws.[B2:B33]
For colNum = 2 To 17 ' B to Q
targetRange.Offset(0, colNum - 1).Value = WorksheetFunction.Sum(columnToSum.Offset(0, colNum - 2))
Next colNum
Set targetRange = targetRange.Offset(1, 0) ' next row in output
End If
Next ws
End Sub
Function worksheetExists(wsName)
' adapted from http://www.mrexcel.com/forum/excel-questions/3228-visual-basic-applications-check-if-worksheet-exists.html
worksheetExists = False
On Error Resume Next
worksheetExists = (Sheets(wsName).Name <> "")
On Error GoTo 0
End Function
Final(?) edit:
If you want this script to run automatically every time someone makes a change to the workbook, you can capture the SheetChange event by adding code to the workbook. You do this as follows:
open the Visual Basic editor ()
In the project explorer (left hand side of the screen), expand the VBAProject
Right-click on "ThisWorkbook", and select "View Code"
In the window that opens, copy/paste the following lines of code:
Private Sub Workbook_SheetChange(ByVal Sh As Object, ByVal Target As Range)
' handle errors gracefully:
On Error GoTo errorHandler
' turn off screen updating - no annoying "flashing"
Application.ScreenUpdating = False
' don't respond to events while we are updating:
Application.EnableEvents = False
' run the same sub as before:
aggregateRaw
' turn screen updating on again:
Application.ScreenUpdating = True
' turn event handling on again:
Application.EnableEvents = True
Exit Sub ' if we encountered no errors, we are now done.
errorHandler:
Application.EnableEvents = True
Application.ScreenUpdating = True
' you could add other code here... for example by uncommenting the next two lines
' MsgBox "Something is wrong ... " & Err.Description
' Err.Clear
End Sub
Kindly use RDBMerge add-in which will combine the data from different worksheet and create a master sheet for you. Please see the below link for more details.
http://duggisjobstechnicalstuff.blogspot.in/2013/03/how-to-merge-all-excel-worksheets-with.html
Download RDBMerge
You can use the indirect function to reference the sheet name. In the image below this function takes the header name (B37) and uses it as the sheet reference. All you have to do is choose the correct "total cell" which I made "A1" in "MAY_2013". I put an image below to show you my reference name as well as tab name

Resources