Home » excel » c# – first blank row in excel

c# – first blank row in excel

Posted by: admin March 9, 2020 Leave a comment

Questions:

Is there a way to find first available blank row in excel sheet using vsto or c# ?
I have been searching for hours but cant find any thing related to it.
Any help in this regard will be greatly appreciated

How to&Answers:

If App is your excel application, you can loop throught the rows starting from number 1 and look for the first empty using CountA function (it returns the number of non empty cells for a Range):

int rowIdx = 0;
int notEmpty = 1;
while (notEmpty > 0)
{
    string aCellAddress = "A" + (++rowIdx).ToString();
    Range row = App.get_Range(aCellAddress, aCellAddress).EntireRow;
    notEmpty = _App.WorksheetFunction.CountA(row);
}

When the while loop exits, rowIdx is the index of the first empty row.

CountA receive other 29 optional arguments, so it is possible that you have to pass Missing.Value 29 times with earlier versions of the framework.

Answer:

Excel.Worksheet xlWorkSheet1 = (Excel.Worksheet)excelbk.Worksheets["Sheet1"];
xlRange = (Excel.Range)xlWorkSheet1.Cells[xlWorkSheet1.Rows.Count, 1];
long lastRow = (long)xlRange.get_End(Excel.XlDirection.xlUp).Row;
Long newRow = lastRow + 1

Code from this link: http://social.msdn.microsoft.com/Forums/pl/exceldev/thread/90384567-3338-4c56-bc6b-70db94d8cbcc

Answer:

There’s a Range.End property or Range.get_End method which combined with a direction will give you the first blank cell in a range.

Have a look at this question for a possible solution: How to find the Next blank row in Excel sheet programatically using C#
The key bit being:

Excel.Worksheet xlWorkSheet1 = (Excel.Worksheet)excelbk.Worksheets["Sheet1"];
xlRange = (Excel.Range)xlWorkSheet1.Cells[xlWorkSheet1.Rows.Count, 1];
long lastRow = (long)xlRange.get_End(Excel.XlDirection.xlUp).Row;
Long newRow = lastRow + 1

But if you’ve got a column that you know will always have every cell filled until the last one then you could get the end in the down direction.