How to merge Worksheets from Multiple Workbooks into New WorkBook

给你一囗甜甜゛ 提交于 2021-01-29 09:11:28

问题


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");

回答1:


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".



来源:https://stackoverflow.com/questions/53728414/how-to-merge-worksheets-from-multiple-workbooks-into-new-workbook

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!