根据条件删除行

时间:2013-07-17 17:10:23

标签: c# excel excel-interop

我在C#编码并使用Microsoft.Office.Interop.Excel。我有列A-F,有些行在列B中没有任何值。所以我想循环遍历列B并查找没有文本/值的所有单元格,然后删除整行。 我想要循环遍历B列并找到空单元格,但是当我尝试删除该行时 - 没有任何反应。这是我的代码:

Excel.Range B = objsheet.get_Range("B1:B" + lastUsedRow, System.Type.Missing);
foreach (Excel.Range r in B)
{
    string column = r.Text.ToString();

    if (string.IsNullOrEmpty(column))
    {
        Excel.Range BEntireRow = objsheet.get_Range(r + "1:" + r + "B" + lastUsedColumn, System.Type.Missing);
        //  Excel.Range BEntireRow2 = r.EntireRow;
        BEntireRow.Delete(Microsoft.Office.Interop.Excel.XlDirection.xlUp);

    }
}

2 个答案:

答案 0 :(得分:2)

您可以执行以下操作,而不是遍历列。这是VBA代码:

Range("B1:B" + lastUsedRow).SpecialCells(xlCellTypeBlanks).EntireRow.Delete

在C#中你会使用:

.SpecialCells(Excel.XlCellType.xlCellTypeBlanks)

BTW我不会命名你的Excel.Application对象Excel - 我会使用xl甚至是myXl。否则会引起混淆,并可能在某些时候导致错误。

已添加完整的C#语句

Range("B1:B" + lastUsedRow).SpecialCells(Excel.XlCellType.xlCellTypeBlanks).EntireRow.Delete();

答案 1 :(得分:0)

尝试这样的事情:

Rows([INSERT_THE_ROW_YOU_WANT_TO_DELETE_HERE]).EntireRow.Delete;
相关问题