在包含搜索文本的行中删除Excel中的所有行

时间:2014-05-01 10:18:29

标签: excel vba excel-vba

我的电子表格中包含不同数量的行。在电子表格上有用的信息的底部是一行名为" Terminations",后面跟着我感兴趣的不同行数。

如何编写VBA脚本来搜索" Terminations"并删除之后的所有行?

我可以搜索" Terminations"像这样:

  Cells.Find(What:="Terminations", After:=ActiveCell, LookIn:=xlFormulas, _
        LookAt:=xlPart, SearchOrder:=xlByRows, SearchDirection:=xlNext, _
        MatchCase:=False, SearchFormat:=False).Activate

我可以删除这样的行:

Rows("245:246").Select
    Selection.Delete Shift:=xlUp

然而,到目前为止,我将这两者结合起来的尝试却毫无结果。

1 个答案:

答案 0 :(得分:1)

试试这个:

Sub test()
    Dim rng As Range
    Dim lastRow As Long

    'change Sheet1 to suit
    With ThisWorkbook.Sheets("Sheet1")
        'find Terminations
        Set rng = .Cells.Find(What:="Terminations", _
                          After:=.Range("A1"), _
                          Lookat:=xlPart, _
                          LookIn:=xlFormulas, _
                          SearchOrder:=xlByRows, _
                          SearchDirection:=xlPrevious, _
                          MatchCase:=False)
        'if Terminations NOT found - exit from sub
        If rng Is Nothing Then Exit Sub
        'find last row
        If Application.WorksheetFunction.CountA(.Cells) <> 0 Then
            lastRow = .Cells.Find(What:="*", _
                          After:=.Range("A1"), _
                          Lookat:=xlPart, _
                          LookIn:=xlFormulas, _
                          SearchOrder:=xlByRows, _
                          SearchDirection:=xlPrevious, _
                          MatchCase:=False).Row
        Else
            lastRow = 1
        End If
        'I use lastRow + 1 to prevent deletion "Terminations" when it is on lastrow
        .Range(rng.Row + 1 & ":" & lastRow + 1).Delete Shift:=xlUp
    End With
End Sub

如何从here

确定lastRow