在Excel中使用VBA删除基于多个单元格值的行

我试图删除在列A中为空的行,而不是在整个Excel表中的列B中为空。

这是因为我需要保持在A中有值的行,但是我也需要保留没有任何内容的行(它们是我的分隔符)。

我试过这个:

Sub DoStuffIfNotEmpty() If Not IsEmpty(Colmuns("B").Value) Then ActiveCell.Columns("A").SpecialCells(xlBlanks).EntireRow.Delete End If End Sub 

其中删除了我的垫片

我试过这个:

 Sub QuickCull() On Error Resume Next Columns("A").Columns("B").SpecialCells(xlBlanks).EntireRow.Delete End Sub 

这将删除这个标准的行之一

我试过这个:

 Sub delete_Me() Dim LastRow As Long, x As Long LastRow = Cells(Rows.Count, "A").End(xlUp).Row For x = LastRow To 1 Step -1 If Not IsEmpty(Colmuns("B").Value) And _ Columns("A").Value Then Rows(x).Delete End If Next End Sub 

哪个什么都不做

如果有人能把我指向正确的方向,那就太棒了!

尝试这样的事情:

 Sub removeRows() Dim LastRow As Long Dim rowNum As Integer LastRow = Cells(Rows.Count, "B").End(xlUp).Row For rowNum = LastRow To 1 Step -1 If Range("B" & rowNum).Value <> "" And Range("A" & rowNum).Value = "" Then Rows(rowNum).Delete End If Next rowNum End Sub 

正如@findwindow和@Jeeped指出的那样,循环应该从最下面的一行开始到最上面。 我的错。 此外,我调整了LastRow使用列“B”计数。

可能使用Count或counta

 Sub Button1_Click() Dim LstRw As Long, Rng As Range LstRw = Cells(Rows.Count, "A").End(xlUp).Row For x = LstRw To 1 Step -1 If Application.WorksheetFunction.Count(Range(Cells(x, 1), Cells(x, 2))) = 0 Then Rows(x).Delete Next End Sub 

使用Range.AutoFilter方法 。 筛选列A上的空白和筛选列B上的非空白。检查是否有要删除的行后,删除它们。

 Sub del_blankA_valueB() With Worksheets("Sheet1") If .AutoFilterMode Then .AutoFilterMode = False With .UsedRange.Cells .AutoFilter field:=1, Criteria1:="=" .AutoFilter field:=2, Criteria1:="<>" With .Resize(.Rows.Count - 1, .Columns.Count).Offset(1, 0) If CBool(Application.CountA(.Columns(2))) Then .Cells.EntireRow.Delete End If End With End With If .AutoFilterMode Then .AutoFilterMode = False End With End Sub