如何将多个工作簿中的工作表合并到新工作簿中

How to merge Worksheets from Multiple Workbooks into New WorkBook

我想合并来自多个工作簿的多个工作表的数据。 例如,我有多个包含多个工作表的工作簿。

所以考虑我想合并 "WorkBook1" 的 "Worksheet1" 的数据和 "Workbook2" 的 "Worksheet2" 的数据,并分别合并到 New [=] 的 "NewWorkSheet" 22=]。我想以一种将数据插入到 "NewWorkSheet" 中的方式执行此操作,就像 "Worksheet1" 中的前 20 行然后 接下来的 20 个来自 "Worksheet2" 等等...

我只能从一个工作表中合并到一个新的工作表中,而不能从其他工作表中合并。

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

对于您希望从 复制的每个后续工作表(请注意,对于第一个工作表,NOT),插入以下代码示例"from.Copy(to);" 和 "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);

问题是您试图将整个列从源工作表复制到目标工作表,从而覆盖目标工作表中的值。此代码仅复制一定范围的单元格,而不是整个数据列。

此外,您的变量名称中有错字 "destionationworkBook"。应该是 "destinationworkBook".