ashish
ashish

Reputation: 23

How to merge Worksheets from Multiple Workbooks into New WorkBook

I want to merge data from multiple worksheets of multiple workbooks. For example, I have multiple Workbooks with multiple worksheets.

So consider I want to merge data from "Worksheet1" of "WorkBook1" and data from "Worksheet2" of "Workbook2" and respectively into "NewWorkSheet" of New "WorkBook". I want to do this in a way that data is inserted into "NewWorkSheet" one below the other, like the first 20 rows from "Worksheet1" then next 20 from "Worksheet2" and so on...

I could merge into a new one only from one worksheet only but not from others.

Workbook xlWorkbookDLA3 = xlApp.Workbooks.Open(dropBoxPath + "Week49DLA3.xlsm");
Worksheet worksheetDLA3 = xlWorkbookDLA3.Worksheets["Wed-A"];

Workbook xlWorkbookDLA4 = xlApp.Workbooks.Open(dropBoxPath + "Week49DLA4.xlsm");
Worksheet worksheetDLA4 = xlWorkbookDLA4.Worksheets["Thurs-A"];

Workbook destionationworkBook = xlApp.Workbooks.Open(dropBoxPath + "Test.xlsm");
Worksheet destworkSheet = destionationworkBook.Worksheets["Sheet2"];

Microsoft.Office.Interop.Excel.Range from, to;


from = worksheetDLA3.Range["B7:S7"].EntireColumn;
to = destworkSheet.Range["B7:S7"].EntireColumn;

from.Copy(to);


destionationworkBook.SaveAs(@"C:\Users\ashish.mokadam\Desktop\DropBox\Test" + ".xlsm");

Upvotes: 0

Views: 173

Answers (1)

Kyle Ross
Kyle Ross

Reputation: 97

For each subsequent worksheet you wish to copy from (note, NOT for the 1st worksheet), insert the following code sample between "from.Copy(to);" and "destionationworkBook.SaveAs(...":

     var destination_start_row = destworkSheet.UsedRange.Rows.Count + 1;  // + 1 because Excel is 1-indexed
     var source_used_rows      = worksheetDLA4.UsedRange.Rows.Count;

     from = worksheetDLA4.Range["B1:S" + source_used_rows];
     to   = destworkSheet.Range["B" + destination_start_row + ":S" + destination_start_row + source_used_rows];
     from.Copy(to);

The problem is that you are trying to copy entire columns from the source worksheets to the destination worksheet, thus overwriting the values in the destination worksheet. This code only copies a range of cells, not entire columns of data.

Also, you have a typo in your variable name "destionationworkBook". It should be "destinationworkBook".

Upvotes: 2

Related Questions