[英]Excel VBA delete entire row if both columns B and C are blank
I'm trying to delete an entire row in excel if column B and C are blank for that row. 如果B和C列空白,我想在excel中删除整行。 I have this vba code that deletes an entire row if the whole row is blank.
我有这个vba代码,如果整行为空,它将删除整行。 How can I only delete the row if B and C have no value?
如果B和C没有值,如何删除行?
Thank you 谢谢
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
-- Update -- - 更新 -
The problem is solved. 问题已经解决了。 Thanks to izzymo and sous2817
感谢izzymo和sous2817
Here is the current code 这是当前代码
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
As asked for, here is a way to do it without looping: 根据要求,这是一种无需循环的方法:
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
The results should be the same, but this way should be faster, especially if you have a lot of rows. 结果应该是相同的,但是这种方式应该更快,尤其是当您有很多行时。 Obviously, change the column reference to suit your layout and feel free to fancy it up w/ some error checking,etc.
显然,更改列引用以适合您的布局,并通过一些错误检查等来随意看它。
Try this 尝试这个
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
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.