I have now lost several hours of my life working around this bug in Worksheet.Copy method. Sometimes I wonder why I was not worse student and I could be doing something more useful now...
First I tried:
//Break links
System.Array links = (System.Array) ((object)targetWorkbook.LinkSources(XlLink.xlExcelLinks));
if (links != null)
{
for (int i = 1; i <= links.Length; i++)
{
try
{
targetWorkbook.UpdateLink((string)links.GetValue(i),
XlLinkType.xlLinkTypeExcelLinks);
targetWorkbook.BreakLink((string)links.GetValue(i),
XlLinkType.xlLinkTypeExcelLinks);
}
catch (Exception ex)
{
Tools.LogException(ex, "targetWorkbook.BreakLink");
}
}
}
No success and I got even HRESULT error. It was not possible to delete external links even using visual interface of Excel, which probably only swallowed this exception.
Finally this did the trick:
w.Activate();
w.Name = CreateValidWorksheetName(targetSheetName);
w.get_Range("a1").EntireRow.EntireColumn.Copy();
w.get_Range("a1").EntireRow.EntireColumn.PasteSpecial(XlPasteType.xlPasteValues);
w.Range["A1:A1"].Select();
if (targetWorkbook != null)
{
//Unhide all rows and then copy!!!
w.get_Range("a1").EntireRow.EntireColumn.Hidden = false;
w.get_Range("a1").EntireColumn.EntireRow.Hidden = false;
w.Copy(targetWorkbook.Sheets[1], Type.Missing);
//Then hide all rows again
HideRows(true, targetWorkbook.Sheets[1].UsedRange, "***HIDETHISROW***");
HideRows(false, targetWorkbook.Sheets[1].UsedRange, "***HIDETHISCOL***");
It is also important to check that the filetypes of the source workbook the target workbook match (both are xlsx), otherwise you may get:
"Excel cannot insert the sheets into the destination workbook, because it contains fewer rows and columns than the source workbook. To move or copy the data to the destination workbook, you can select the data, and then use the Copy and Paste commands to insert it into the sheets of another workbook."
_ExcelApp.DefaultSaveFormat = Microsoft.Office.Interop.Excel.XlFileFormat.xlOpenXMLWorkbook;