如果单元格值等于“”,如何编写Excel宏以删除整个行

时间:2019-11-05 00:02:27

标签: excel vba

我想有一个宏,它删除多个范围内等于“”的单元格的整行。范围是“ B16:B115,B131:B230,B250:B349”。

逻辑: 如果单元格等于“”,则删除整行。

我希望实际上删除该行,而不仅仅是单元格的内容。

谢谢。

2 个答案:

答案 0 :(得分:0)

这值得一试:

On Error Resume Next
Range("B16:B115,B131:B230,B250:B349").SpecialCells(xlCellTypeBlanks).EntireRow.Delete
On Error Goto 0

取决于“”单元格是否包含公式或是否为空。 Range.SpecialCells: What does xlCellTypeBlanks actually represent?

编辑:如果您有公式,则必须走很长一段路:

Sub DeleteEmpty()

    Dim c As Range, rngDel As Range

    For Each c In Range("B16:B115,B131:B230,B250:B349").Cells
        If Len(c.Value) = 0 Then
            If rngDel Is Nothing Then
                Set rngDel = c
            Else
                Set rngDel = Application.Union(rngDel, c)
            End If
        End If
    Next c

    If Not rngDel Is Nothing Then rngDel.EntireRow.Delete

End Sub

答案 1 :(得分:0)

下面的子菜单将允许您选择范围以删除空白行。

Sub RemoveBlanks()
Dim rng As Range, rws As Long, i As Long
Dim LastRow As Range
Dim myRange As Range

  Set myRange = Application.InputBox(prompt:="Select Header Cell To Remove Blanks.", Type:=8)
  'LastRow = Cells(Rows.Count, "A").End(xlUp).Row
  Set LastRow = Cells(Rows.Count, myRange.Column).End(xlUp)
  Set rng = ActiveSheet.Range(myRange.Address & ":" & LastRow.Address)
  rws = rng.Rows.Count

  For i = rws To 1 Step (-1)
    If WorksheetFunction.CountA(rng.Rows(i)) = 0 Then rng.Rows(i).EntireRow.Delete
  Next

  Set myRange = Nothing
  Set LastRow = Nothing
  Set rng = Nothing

End Sub