VBA to consolidate data from selected multiple worksheets in a different workbook

cloclo

New Member
Joined
Sep 26, 2014
Messages
3
Hi,

I have 2 files. One file is the source of data and the other file is for extraction of the data and analysis. In the first file, I have many worksheets, but I would like to consolidate the data from worksheets, which contains "production" in the worksheet name. The destination of the extracted data will be in the second file, in worksheet "RDBMergeSheet".

How can I modify the macro below to allow me to do this? Would the source file need to be open at the same time as the destination file for the macro to work?

Thank you!

Sub CopyDataWithoutHeaders()
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 summary sheet if it exists.
Application.DisplayAlerts = False
On Error Resume Next
ActiveWorkbook.Worksheets("RDBMergeSheet").Delete
On Error GoTo 0
Application.DisplayAlerts = True

' Add a new summary worksheet.
Set DestSh = ActiveWorkbook.Worksheets.Add
DestSh.Name = "RDBMergeSheet"

' Fill in the start row.
StartRow = 4

' Loop through all worksheets and copy the data to the
' summary worksheet.
For Each sh In ActiveWorkbook.Worksheets
If LCase(Left(sh.Name, 10)) = "production" Then

' Find the last row with data on the summary
' and source worksheets.
Last = LastRow(DestSh)


'Set the range that you want to copy
Set CopyRng = sh.UsedRange

' Test to see whether there are enough rows in the summary
' worksheet to copy all the data.
If Last + CopyRng.Rows.Count > DestSh.Rows.Count Then
MsgBox "There are not enough rows in the " & _
"summary worksheet to place the data."
GoTo ExitTheSub
End If

' This statement copies values and formats.
With CopyRng
DestSh.Cells(Last + 1, "A").Resize(.Rows.Count, _
.Columns.Count).Value = .Value
End With

End If

Next

ExitTheSub:

Application.Goto DestSh.Cells(1)

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

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

ztodd

Board Regular
Joined
Sep 17, 2014
Messages
221
Yeah, I'm pretty sure they both have to be open. Note- a file is the same as a workbook - everywhere you have ActiveWorkbook, it's referring only to the currently open & active file / workbook. If you want to refer to a different workbook that's open, you need to use workbooks("nameOfWorkbook") instead.
 

Forum statistics

Threads
1,086,235
Messages
5,388,624
Members
402,127
Latest member
Jemx

Some videos you may like

This Week's Hot Topics

Top