简体   繁体   中英

How can I evaluate the no. of records in a range of a single excel column in c#?

I am trying an automation work on an excel sheet using c#. I want to delete blank rows present at the end of the excel sheet based on the no. of records in the first column only. Any other column may have different no. of rows than that in the first column. For this purpose first I tried to evaluate the range of the first column and based on that I tried to delete rows after this in the excel sheet. I used the following lines of code for this purpose :-

Range lastrow_new = sourceSheet2.get_Range("A6", Type.Missing);
if (excelApp.WorksheetFunction.CountA((int)(sourceSheet2.Rows[lastrow_new])) == 0)
{
    for (int i = 1; i <= (int)(sourceSheet2.Rows[lastrow_new]); i++)
    {
        if (excelApp.WorksheetFunction.CountA(sourceSheet2.Rows[i]) == 0)
        {
            Range BlankRows = sourceSheet2.get_Range("A" + i + ":" + "FN" + lastrow_new);
            BlankRows.Select();
            BlankRows.EntireRow.Delete();
            i = (int)(sourceSheet2.Rows[lastrow_new]) + 1;
        }
    }
}

But it is giving error of 'Type mismatch'. Can anyone help ? Thanks in advance.

I'm not sure i understand what you want... but if you want clear the consecutive rows after 'A6' column, you can try this code:

            string value = sourceSheet2.Range["A1"].SpecialCells(XlCellType.xlCellTypeLastCell).Address;
            value = value.Replace("$","");
            sourceSheet2.Range["A6", value].ClearContents();    

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM