Delete or Remove Cells from Excel using C#

Delete or Remove Cells from Excel using C#

Delete Cell:

In excel delete or remove cell concept works on Shifting method where cells shift into two directions as explained below, the following actions get determined with “XlDeleteShiftDirection” enum :

  1. Up : it shifts cells up by deleting selected cell using xlShiftUp constant
  2. Left : it shifts cells to left by deleting selected cell using xlShiftToLeft constant

Prerequisites:

  • Visual Studio 2015 or above having Microsoft Office for Developer Tool installed
  • Create Excel Addin in C# code style
  • Create a ribbon designer and put button

Code Example:

private void btnDeleteCell_Click(object sender, RibbonControlEventArgs e)
{
	//capture user selection
	excel.Range oRange = Globals.ThisAddIn.Application.Selection;
	//shift left
	oRange.Cells.Delete(excel.XlDeleteShiftDirection.xlShiftToLeft);

}

Above code will retain selection and second line will determine remove current cell and shifts others to left.

Before code execution:

Post code execution:

Code Example:

private void btnDeleteCell_Click(object sender, RibbonControlEventArgs e)
{
	//capture user selection
	excel.Range oRange = Globals.ThisAddIn.Application.Selection;
	//shift left
	oRange.Cells.Delete(excel.XlDeleteShiftDirection.xlShiftUp);

}

In above code we are using Shift Up method and output should be as follow. Before code execution:

Post code execution:

Please leave your valuable comments:

Next: How to delete row in Excel using C# VSTO

Leave a Reply

Your email address will not be published.