如果列B和C都为空,则Excel VBA删除整行
我试图删除Excel中的整个行,如果列B和C对于该行是空白的。 我有这个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
正如所要求的,这里是一个没有循环的方法:
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
结果应该是一样的,但这种方式应该更快,特别是如果你有很多行。 很显然,改变列引用以适合你的布局,并随意看看它有一些错误检查等。
尝试这个
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