Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

first blank row in excel

Tags:

c#

excel

vsto

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

like image 713
John Avatar asked May 25 '12 10:05

John


3 Answers

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

like image 112
Neil_M Avatar answered Sep 24 '22 13:09

Neil_M


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.

like image 31
Francesco Baruchelli Avatar answered Sep 22 '22 13:09

Francesco Baruchelli


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.

like image 25
Nanhydrin Avatar answered Sep 24 '22 13:09

Nanhydrin