简体   繁体   English

如果特定范围内的单元格全部为空,则删除整行

[英]Delete entire row if cells in specific range are all empty

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. 我想创建一个宏,如果特定范围内的所有单元格(10行中每一行中的B到K)都为空,则会删除整行。 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. 如果有更多的后续行与空单元格,让我们说1和2,它删除第1行并移动第2行而不是删除的第1行,所以它变成第1行。然后它跳过移动的行,因为我总是增加所以它永远不会再次检查第1行。 Is there any way to check if the row that was just deleted is really non-empty before moving to the next i? 在移动到下一个i之前,有没有办法检查刚删除的行是否真的非空?

Btw: I am using Excel 2013. 顺便说一句:我正在使用Excel 2013。

Instead of using the Special Cells, why not just use CountA() ? 而不是使用特殊单元格,为什么不使用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. 此外,删除行时,建议从最后开始,然后从Step -1开始。

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. 我建议首先使用F8逐步完成,看看它是如何工作的。 In the range B1:K10 , it will first select all rows where there's a blank cell. B1:K10范围内,它将首先选择所有有空白单元格的行。 Then, it'll delete those rows. 然后,它将删除这些行。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM