Reputation: 109
I'm a new programmer to VBA. I am using a simple line to delete rows out of a for-loop I've made. This simple line deletes the current row.
Rows(i).EntireRow.Delete
I however have content in column D that I don't want deleted. Is there a way to justify "EntireRow" to something else like "A,B,C"?
a b c d
1 x x x N
2 x x x N
3 x x x N
X = don't need. N = needed.
Upvotes: 0
Views: 692
Reputation: 22866
If you Record Macro, you get something like:
Selection.Delete Shift:=xlUp
so here are few options:
Rows(i).Resize(, 3).Delete xlUp
Range("A:C").Rows(i).Delete xlUp
Range("A1:C1").Offset(i - 1).Delete xlUp
Upvotes: 6
Reputation: 386
Try this VBA code:
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
Be sure to save a backup before you begin. :)
Upvotes: 0