如果有2个连续的空行,则删除行

时间:2019-12-03 03:33:57

标签: excel vba

我要删除的行是连续有2个连续的空行,并且还需要删除标题和第一组数据行之间的空行。 input,我想拥有的是this。我试图在这里和那里找到一些代码,并提出这个代码。

Sub Testing()
    Dim i As Long , lRow As Long
    Dim ws As Worksheet

    Set ws = Activesheet
    With ws
        With .Range("C:C")
            fr = .Find(what:="*", after:=.Cells(1, 1), LookIn:=xlValues).row
            If fr > 2 Then
                .Rows("2:" & fr - 1).EntireRow.Delete
            End If
        End With
        i = 1
        For i = 1 To lRow
            If IsEmpty(Cells(i, 3)) And IsEmpty(Cells(i + 1, 3)) Then
                .Rows(i).EntireRow.Delete
           End If
        Next i
    End With
End Sub

但是,数据集的中间仍然有一些连续的空行。我知道这是因为我正在增加i,它将查看下一个单元格,但是我不确定如何解决它。我是vba的新手,还是SO发布的新手,所以让我知道我做错了什么,谢谢您的帮助。

3 个答案:

答案 0 :(得分:3)

您唯一需要做的就是向后循环。代替

For i = 1 To lRow

For i = lRow To 1 Step -1

这是因为从底部循环对尚未处理的行的行计数没有任何影响,但是从顶部到底部循环却有影响。

您也可以在i = 1之前跳过For,因为For以指定为下限的i开始,因此没有任何影响。

我认为您的代码只是一个示例,但以防万一请注意,lRow从未在您的代码中设置为值,因此为0


请注意,在这一行

If IsEmpty(Cells(i, 3)) And IsEmpty(Cells(i + 1, 3)) Then

您的Cells对象未引用到With语句的表中,因为您一开始就忘记了.。应该是

If IsEmpty(.Cells(i, 3)) And IsEmpty(.Cells(i + 1, 3)) Then

此外,我强烈建议,如果您使用Range.Find method

fr = .Find(what:="*", after:=.Cells(1, 1), LookIn:=xlValues).row

始终LookAt参数指定为xlWholexlPart(请参见XlLookAt)。因为LookAt参数没有默认值(很遗憾),并且如果您未指定默认值,则VBA将使用xlWholexlPart 上次使用的 >通过用户界面或VBA。因此,您不知道以前使用过哪个代码,它会变得非常随机(否则您的代码有时可能会工作,有时则不会)。


替代方法(快得多)...

…是保持正向循环,并收集所有要删除的行到变量RowsToDelete中,以便最后删除它们。之所以如此快,是因为每个删除操作都需要时间,并且在这种方法中,您只有一个删除操作…与另一种方法中的每行删除操作

Dim RowsToDelete As Range
For i = 1 To lRow 'forward loop is no issue here because we just collect
    If IsEmpty(.Cells(i, 3)) And IsEmpty(.Cells(i + 1, 3)) Then
        If RowsToDelete Is Nothing Then 'first row
            Set RowsToDelete = .Rows(i).EntireRow
        Else 'append more rows with union
            Set RowsToDelete = Application.Union(RowsToDelete, .Rows(i).EntireRow)
        End If
   End If
Next i

'delete all collected rows (after the loop, so delete doesn't affect row counting of the loop)
If Not RowsToDelete Is Nothing Then
    RowsToDelete.Delete
End If

答案 1 :(得分:1)

我认为您需要在删除一行后减少i

For i = 1 To lRow
    If IsEmpty(Cells(i, 3)) And IsEmpty(Cells(i + 1, 3)) Then
       .Rows(i).EntireRow.Delete
       i = i - 1
       lRow = lRow - 1
    End If
   If i > lRow Then Exit For
Next i

答案 2 :(得分:-1)

Dim blankCtr As Integer
blankCtr = 0

With ActiveSheet
For i = .Range("A" & Rows.Count).End(xlUp).Row To 2 Step -1
  If Application.WorksheetFunction.CountA(Rows(i)) = 0 Then
   blankCtr = blankCtr + 1
  If .Rows(i).Cells(1).End(xlUp).Row = 1 Then
  .Rows(i & ":" & .Rows(i).Cells(1).End(xlUp).Offset(1).Row).Delete
  Exit Sub
 End If

If blankCtr > 1 Then
.Rows(i).Delete
blankCtr = blankCtr - 1
End If

Else
blankCtr = 0
GoTo here

End If

here:
Next i
End With