删除特定文字下方的行

时间:2018-12-13 10:23:03

标签: excel vba

当A列中的单元格值具有特定文本时,我试图删除下面显示的一行。

Sub DeleteRowWithContentsGuidelines()
    Dim c As Range
    Dim SrchRng
    Set SrchRng = ActiveSheet.Range("A1", ActiveSheet.Range("A65536").End(xlUp))
    Do
        Set c = SrchRng.Find("Chart only", LookIn:=xlValues)
        If Not c Is Nothing Then c.EntireRow.Delete
    Loop While Not c Is Nothing
End Sub

上面的行删除文本中具有“仅图表”的行,但是我想删除下面的行,但不删除确切的行。这可能吗?

2 个答案:

答案 0 :(得分:2)

.Find返回一个范围对象,因此您可以使用如下所示的方法删除找到的文本下方的行:

Sub DeleteRowWithContentsGuidelines()
    Dim c As Range
    Dim SrchRng
    Set SrchRng = ActiveSheet.Range("A1", ActiveSheet.Range("A" & Activesheet.Rows.Count).End(xlUp))
    Set c = SrchRng.Find("Chart only", LookIn:=xlValues)
    If c is Nothing then Exit Sub
    dim firstAddress : firstAddress = c.Address
    Do
        If Not c Is Nothing Then c.Offset(1, 0).EntireRow.Delete
        Set c = SrchRng.FindNext(c)
        If c is Nothing then Exit Sub
    Loop While c.Address <> firstAddress
End Sub

答案 1 :(得分:2)

Sub DeleteRowWithContentsGuidelines()
    Dim c As Range, rDel As Range, i As Long
    Dim SrchRng As Range, s1 As String

    Set SrchRng = ActiveSheet.Range("A1", ActiveSheet.Range("A" & Rows.Count).End(xlUp))
    s1 = "Chart only"

    With SrchRng
        Set c = .Cells(1)
        For i = 1 To WorksheetFunction.CountIf(.Cells, s1)
            Set c = .Find(What:=s1, After:=c, LookAt:=xlPart, MatchCase:=False, SearchFormat:=False)
            If Not c Is Nothing Then
                If rDel Is Nothing Then
                    Set rDel = c.Offset(1)
                Else
                    Set rDel = Union(rDel, c.Offset(1))
                End If
            End If
        Next i
        rDel.EntireRow.Delete
    End With
End Sub