2013-07-17 154 views
0

我在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); 

    } 
} 
+0

我編輯了自己的冠軍。請參閱:「[應該在其標題中包含」標籤「](http://meta.stackexchange.com/questions/19190/)」,其中的共識是「不,他們不應該」。 –

回答

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(); 
+0

這是幹什麼的? .SpecialCells(Excel.XlCellType.xlCellTypeBlanks) - 刪除單元格? – user2140832

+0

這是什麼問題:Excel.Range BEntireRow = objsheet.get_Range(「B1:B」+ lastUsedRow,System.Type.Missing); BEntireRow.SpecialCells(Excel.XlCellType.xlCellTypeBlanks).EntireRow.Delete; – user2140832

+0

任何解決方案,即時消息不完全實現您的代碼 – user2140832

0

嘗試這樣:

Rows([INSERT_THE_ROW_YOU_WANT_TO_DELETE_HERE]).EntireRow.Delete; 
+0

在'EntireRow'之前加一個點:D – chancea

+0

please,它像我一樣死囚並且不能編輯只有一個字符 – chancea