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

时间:2014-09-16 15:07:19

标签: excel vba excel-vba

让我说我的范围 $ A $ 1:$ A $ 10 就像这样。 (每次都会有所不同)

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

现在,我希望以某种方式删除空单元格,使其看起来像这样 我需要一直删除"删除此" 单元格。

   |  A          B
-------------------
 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

有没有简单的方法可以做到这一点......?

2 个答案:

答案 0 :(得分:1)

如果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

答案 1 :(得分:1)

我无法告诉您用于删除行的确切条件,但只有当两列都为空时或者如果列A为空且列B具有&#时,它才显示出来34;删除这个"在里面。假设情况如此,我将使用以下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