richard smith

richard smith

  • 1.5k
  • 285
  • 160.2k

C# To Insert 3 Rows in Excel

Mar 18 2013 1:52 PM
I am running the below code attempting to insert 3 rows in Excel, but it gives me the debug error of:
COMException was unhandled
private static _Application docExcel;
public static void AddThreeRows()
{
long i;
for(i = (int)(docExcel.Cells[docExcel.Rows.Count, "e"].End(XlDirection.XxlUp).Row); i >= 3; i--)
{
string e1 = docExcel.Cells[i, "E"].Value;
if (!string.IsNullOrEmpty(e1.ToUpper()))
{
string em1 = docExcel.Cells[i - 1, "e"].Value;
if (e1 != em1)
{
docExcel.Rows.Insert(Excel.XlInsertShiftDirection.xlShiftDown);
}
}
}
}

What I am trying to do here is each time there is a different value in "E" add 3 rows....so for example if Column E reads:
Joseph
Joseph


Brian
Brian
Brian
Brian
Brian


Mark
Mark
Mark

etc

Answers (7)