简体   繁体   中英

C# Excel: Issue in copying worksheet from different workbook

I'm currently trying to copy a worksheet from a different workbook which i succeed by using Copy() and PasteSpecial(). However, I would like to know why the following code does not work even though many solutions online seems to use this approach.

 Workbook currBook = Globals.ThisAddIn.GetActiveWorkbook(); Workbook copyBook = Globals.ThisAddIn.OpenWorkbook(Globals.ThisAddIn.Application.ActiveWorkbook.Path + @"\\copyFile.xlsm", true, true); //required worksheet Worksheet copySheet = Globals.ThisAddIn.GetWorksheet(copyBook, "ToCopy"); copySheet.Copy(currBook.Worksheets[1]); //close workbook copyBook.Close(); 

Function used to get specific sheet:

 public Excel.Worksheet GetWorksheet(Excel.Workbook book, string sheetName, bool create = false) { foreach (Excel.Worksheet sheet in book.Worksheets) { //worksheet with name found if (sheet.Name == sheetName) { sheet.Activate(); return sheet; } } //worksheet can't be found if (create) { Excel.Worksheet sheet = book.Worksheets.Add(); sheet.Name = sheetName; sheet.Activate(); return sheet; } return null; } 

There is no error from the stated code and the worksheet has been tested to exist. The program simply does not create a copy into currBook

Interestingly, I was just working on something else where this came up...

In order to specify a destination it's necessary to use Range.Copy , not Sheet.Copy :

copySheet.UsedRange.Copy(currBook.Worksheets[1].Range["A1"]); 

If a destination can't be specified, then Excel puts the data in a new workbook.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM