2016-09-14 163 views
0

我是VBA的新程序員。我正在使用一條簡單的線刪除我製作的for循環中的行。這個簡單的行刪除當前行。使用VBA在Excel中刪除行

Rows(i).EntireRow.Delete 

但是,我有D列中的內容,我不想刪除。有沒有辦法將「EntireRow」證明爲「A,B,C」之類的東西?

a b c d 
1 x x x N 
2 x x x N 
3 x x x N 

X =不需要。 N =需要。

+0

'Range(「A」&i&「:C」&i)' –

回答

6

如果您錄製宏,你喜歡的東西:

Selection.Delete Shift:=xlUp 

所以這裏有幾個選項:

Rows(i).Resize(, 3).Delete xlUp 

Range("A:C").Rows(i).Delete xlUp 

Range("A1:C1").Offset(i - 1).Delete xlUp 
0

試試這個VBA代碼:

Sub Delete_Row_If_Not_Whatever() 
Dim RowToTest As Long 
'Macro deletes entire row if "Whatever" is not found in column "D" 

Application.ScreenUpdating = False 'Turn off screen updating. Code runs faster without screen flicker 

'Column Count 4 = "D" 
For RowToTest = Cells(Rows.Count, 4).End(xlUp).row To 2 Step -1 

'Look for "Whatever" save row and delete other rows. Replace "Whatever" with what you want to keep. 
'Column Count 4 = "D" 
With Cells(RowToTest, 4) 
    If .Value <> "Whatever" _ 
    Then _ 
    Rows(RowToTest).EntireRow.Delete 
End With 

Next RowToTest 

Application.ScreenUpdating = True 'Turn on screen updating 
End Sub 

一定要保存在開始之前進行備份。 :)