You are using 'emptyRow' to define the range, but it's not clear how you are calculating the value for 'emptyRow'.
To find an empty row dynamically, you need to implement a method to identify an empty row index. You need to iterate through the rows in the worksheet and check for an empty row. My example method below called 'FindEmptyRow()' -
int FindEmptyRow(Excel.Worksheet worksheet, int startRow)
{
int lastRow = worksheet.Cells.SpecialCells(Excel.XlCellType.xlCellTypeLastCell).Row;
for (int rowIndex = startRow; rowIndex <= lastRow; rowIndex++)
{
bool isEmptyRow = true;
for (int colIndex = 1; colIndex <= worksheet.Columns.Count; colIndex++)
{
Excel.Range cell = worksheet.Cells[rowIndex, colIndex];
if (cell.Value != null)
{
isEmptyRow = false;
break;
}
}
if (isEmptyRow)
{
return rowIndex;
}
}
return -1;
}
int emptyRow = FindEmptyRow(targetWorksheet, RegGlobals.StartingRow);
if (emptyRow != -1)
{
int intRowIndex;
bool found = false;
for (intRowIndex = RegGlobals.StartingRow; intRowIndex < emptyRow && !found; intRowIndex++)
{
DateTime dtSheetDate = targetWorksheet.Cells[intRowIndex, RegGlobals.intDateCol].Value;
if (DateTime.Parse(txtDate.Text) < dtSheetDate)
{
Excel.Range deleteRange = targetWorksheet.Rows[emptyRow];
string temp1 = deleteRange.Text;
deleteRange.Delete();
targetWorksheet.Rows.Insert(intRowIndex);
found = true;
}
}
}
else
{
}