如果列B和C都为空,则Excel VBA将删除整行

时间:2015-03-09 12:51:54

标签: excel vba excel-vba

如果列B和C为该行的空白,我正在尝试删除excel中的整行。我有这个vba代码,如果整行是空白的,删除整行。如果B和C没有值,我怎么才能删除该行?

谢谢

 Sub DeleteBlank()

 Dim rng
 Dim Lastrow As Integer
 Set rng = Nothing

 Lastrow = Range("A" & Rows.Count).End(xlUp).Row

For Each i In Range("B1:B" & Lastrow)
    If Application.CountA(i.EntireRow) = 0 Then

        If rng Is Nothing Then
            Set rng = i
        Else
            Set rng = Union(rng, i)
        End If
    End If
Next i
MsgBox (Lastrow)
If Not rng Is Nothing Then
    rng.EntireRow.Delete
End If

End Sub

- 的更新 -

问题解决了。感谢izzymo和sous2817

这是当前的代码

Sub DeleteBlank()

 Dim i As Integer
 Dim Lastrow As Integer

 Lastrow = Range("A" & Rows.Count).End(xlUp).Row
 MsgBox (Lastrow)
 For i = Lastrow To 2 Step -1
   If Trim(Range("B" & i).Value) = "" And Trim(Range("C" & i).Value) = "" Then
    Range("B" & i).EntireRow.Select
    Selection.Delete

    End If

  Next i

 MsgBox "Done"

 End Sub

2 个答案:

答案 0 :(得分:2)

正如所要求的,这是一种不循环的方法:

Sub NoLoopDelete()
Dim lr As Long

lr = Range("A" & Rows.Count).End(xlUp).Row
    With Sheet1.Range("A1:I" & lr)
        .AutoFilter
        .AutoFilter Field:=2, Criteria1:="="
        .AutoFilter Field:=3, Criteria1:="="
        .Offset(1).SpecialCells(xlCellTypeVisible).EntireRow.Delete
        .AutoFilter
    End With
End Sub

结果应该是相同的,但这样应该更快,特别是如果你有很多行。显然,更改列引用以适合您的布局,并随意使用某些错误检查等等。

答案 1 :(得分:1)

试试这个

Sub DeleteBlank()

 Dim i as Integer
 Dim Lastrow As Integer

 Lastrow = Range("A" & Rows.Count).End(xlUp).Row

For i = 2 To Lastrow
    If Trim(Range("B" & i).Value) = "" And Trim(Range("CB" & i).Value) = "" Then
     Range("B" & i).EntireRow.Select
     Selection.Delete
     i = i - 1
    End If

Next i

MsgBox "Done"

End Sub