如何从范围删除空单元格?

比方说,我有这样的范围$ A $ 1:$ A $ 10 。 (每次都会有所不同)

| AB ------------------- 1 | a 1 2 | b 2 3 | 4 | c 5 | 6 | Delete this 7 | d 4 8 | 9 | e 10 | f 5 

现在,我想以某种方式删除空单元格,使其看起来像这样。
我需要一直删除“删除这个”单元格。

  | AB ------------------- 1 | a 1 2 | b 2 4 | c 5 | d 4 6 | e 7 | f 5 

到目前为止,我已经使用这个,但我没有得到我想要的。

 Sub test() Dim lastrow As Long Dim cell As Range Dim rng As Range 'change sheet name to suit With ThisWorkbook.Worksheets("ws") 'find lastrow in columns A:B lastrow = Application.Max(.Cells(.Rows.Count, "A").End(xlUp).Row, _ .Cells(.Rows.Count, "B").End(xlUp).Row) 'Iterates throught each cell in D:E and if it equals to "" For Each cell In .Range("A:B" & lastrow) If (cell.Value = "") Or (cell.Value = "Delete this") Then If rng Is Nothing Then Set rng = cell Else Set rng = Union(rng, cell) End If End If Next 'delete all empty cells (with "") If Not rng Is Nothing Then rng.Delete Shift:=xlUp End With End Sub 

有没有简单的方法来做到这一点…?

我不能告诉你用来删除一行的确切条件,但是只有当两列都是空的,或者列A是空的,而列B中有“删除这个”的时候,它才会出现。 假设是这样,我会使用下面的Do-Loop

 Sub test() Dim lastrow As Long 'change sheet name to suit With ThisWorkbook.Worksheets("ws") 'find lastrow in columns A:B lastrow = Application.Max(.Cells(.Rows.Count, "A").End(xlUp).Row, _ .Cells(.Rows.Count, "B").End(xlUp).Row) 'Iterates throught each cell in D:E and if it equals to "" ActiveSheet.Range("A1").Select Do If (ActiveCell.Value = "" And (ActiveCell.Offset(0, 1).Value = "" Or ActiveCell.Offset(0, 1).Value = "Delete This")) Then ActiveCell.EntireRow.Delete ActiveCell.Offset(-1, 0).Select lastrow = lastrow - 1 End If ActiveCell.Offset(1, 0).Select Loop Until (ActiveCell.Row = lastrow) End With End Sub 

看起来行删除的条件是如果A和B是空的或B有删除这个 。 尝试这种修改。

 Sub test() Dim r As Long, lr As Long With ThisWorkbook.Worksheets("ws") 'find lastrow in columns A:B lr = Application.Max(.Cells(.Rows.Count, "A").End(xlUp).Row, _ .Cells(.Rows.Count, "B").End(xlUp).Row) 'Iterates throught each row in A:B and if it equals to "" For r = lr To 1 Step -1 If Not CBool(Len(.Cells(r, 1).Value & .Cells(r, 2).Value)) Or _ LCase(.Cells(r, 2).Value) = "delete this" Then .Rows(r).EntireRow.Delete End If Next End With End Sub