使用VBA - MS Excel删除空行

时间:2015-06-27 19:31:27

标签: excel vba excel-vba

我希望看看是否有更有效的方法来实现下面的结果,因此可以根据需要进行扩展。

我正在使用它来清理C-Z行空白的大型电子表格。我想应该有一种清理它的方法,这样如果我需要清理一个包含从C到AZ的数据的电子表格,它就不必加倍。

自从我使用VBA已经有一段时间了,我在网上找到了以下代码。 (计算ROW B作为有问题的电子表格有一个空的行A)

Sub delem()
Dim lr As Long, r As Long
lr = Cells(Rows.Count, "B").End(xlUp).Row
For r = lr To 1 Step -1
    If Range("C" & r).Value = "" And Range("D" & r).Value = "" And Range("E" & r).Value = "" And Range("F" & r).Value = "" And Range("G" & r).Value = "" And Range("H" & r).Value = "" And Range("I" & r).Value = "" And Range("J" & r).Value = "" And Range("K" & r).Value = "" And Range("L" & r).Value = "" And Range("M" & r).Value = "" And Range("N" & r).Value = "" And Range("O" & r).Value = "" And Range("P" & r).Value = "" And Range("Q" & r).Value = "" And Range("R" & r).Value = "" And Range("S" & r).Value = "" And Range("T" & r).Value = "" And Range("U" & r).Value = "" And Range("V" & r).Value = "" And Range("W" & r).Value = "" And Range("X" & r).Value = "" And Range("Y" & r).Value = "" And Range("Z" & r).Value = "" Then Rows(r).Delete
Next r
End Sub

谢谢!

2 个答案:

答案 0 :(得分:2)

只需添加内部循环即可浏览您关注的列。这实际上会更快地运行,因为VBA不会使If语句短路(所有条件都被评估)。但是对于循环,如果你在任何地方找到一个值,你可以提前退出:

Sub delem()
    Dim last As Long
    Dim current As Long
    Dim col As Long
    Dim retain As Boolean

    last = Cells(Rows.Count, "B").End(xlUp).Row
    For current = last To 1 Step -1
        retain = False
        For col = 3 To 26
            If Cells(current, col).Value <> vbNullString Then
                retain = True
                Exit For
            End If
        Next col
        If Not retain Then Rows(current).Delete
    Next current
End Sub

答案 1 :(得分:0)

Excel工作表函数COUNTA是一种测试范围是否为空的简洁方法。

Sub delem()
  Dim lr As Long, r As Long
  lr = Cells(Rows.Count, "B").End(xlUp).Row
  For r = lr To 1 Step -1

    'This function Counts the number of cells that are not empty
    If WorksheetFunction.CountA(Range(Cells(r, 3), Cells(r, 26)) = 0 Then 
      Rows(r).Delete 
    End If

  Next r
End Sub