I want to create a macro that would delete an entire row if all the cells in specific range (B to K in each of the 10 rows) are all empty. I tried the following:
Dim i As Integer
Dim rng As Range
For i = 1 To 10
Set rng = Range("B" & i, "K" & i).SpecialCells(xlCellTypeBlanks)
rng.EntireRow.Delete
Next i
If there are more following lines with empty cells, let's say 1 and 2, it deletes row 1 and move row 2 instead of the deleted one, so it becomes row 1. Then it skips the moved row, because i always increases so it never checks row 1 again. Is there any way to check if the row that was just deleted is really non-empty before moving to the next i?
Btw: I am using Excel 2013.
Answer
Instead of using the Special Cells, why not just use CountA()
?
Sub t()
Dim i&
For i = 10 To 1 Step -1
If WorksheetFunction.CountA(Range("B" & i, "K" & i)) = 0 Then
Rows(i).EntireRow.Delete
End If
Next i
End Sub
That way, you can avoid any errors in case there's no blanks. Also, when deleting rows, it's recommended to start at the end, then Step -1
to the beginning.
Edit:
Try this as well, it may be quicker:
Sub T()
Dim rng As Range
Set rng = Range("B1:K10") ' Since you're going to loop through row 1 to 10, just grab the blank cells from the start
rng.SpecialCells(xlCellTypeBlanks).EntireRow.Select ' Just to show you what's being selected. Comment this out in the final code
rng.SpecialCells(xlCellTypeBlanks).EntireRow.Delete
End Sub
I recommend stepping through that with F8 first, to see how it works. In the range B1:K10
, it will first select all rows where there's a blank cell. Then, it'll delete those rows.
No comments:
Post a Comment