Excel Interop - Cancel selection

2019-02-26 01:58发布

问题:

I'm copying and inserting rows in an Excel sheet, like so:

   while (rowsToAdd > 0)
   {
      // copy the existing row
      insertionCell.EntireRow.Copy(Type.Missing);

      // location of the new row
      Range newRow = insertionCell.EntireRow.get_Offset(1, 0).EntireRow;

      // insert the new row
      newRow.Insert(XlInsertShiftDirection.xlShiftDown, Type.Missing);

      rowsToAdd--;
   }

The problem I have is that sometimes, I'm left with a selection marquee around the row I originally copied.

Is there a way I can cancel the selection marquee (the way you'd normally do it with the Escape key?)

回答1:

In VBA it's Application.CutCopyMode = False



回答2:

Adding

myExcelApplication.CutCopyMode = XlCutCopyMode.xlCopy;

seems to do the trick, though the documentation does not explain it very well, and seems to be wrong, since bools are mentioned.



回答3:

I know it's pretty old, but as I had some issue copying one row to another, and as I got the proper solution on my case, I'm now glad to share it, just in case it could fix your problem (thinking about copy rows instead of inserting one).

Here is the solution:

Microsoft.Office.Interop.Excel.Range xlSourceRow;
Microsoft.Office.Interop.Excel.Range xlNewRow;
xlSourceRow.Copy(xlNewRow);

Using this solution prevents from getting any selection in your MS-Excel file.