VBA根据单元值删除行

时间:2018-09-06 08:21:34

标签: excel vba excel-vba

enter image description here我编写了以下代码,我想在B列中找到值“ BEST Cards Raised:”,并且无论在何处删除该值以及B列中所有包含数据的行。 / p>

我以为我写的东西行得通,但是它当前删除了所有行,我无法弄清楚:(

Dim lastRow As Long, found As Range
With ActiveSheet

    Set found = .Range("B1:B" & .Cells(.Rows.Count, "B").End(xlUp).Row).Find("BEST Cards Raised:")
    If Not found Is Nothing Then
        lastRow = .Cells.Find(What:="*", _
                              After:=.Cells(1, 1), _
                              Lookat:=xlPart, _
                              LookIn:=xlFormulas, _
                              SearchOrder:=xlByRows, _
                              SearchDirection:=xlPrevious, _
                              MatchCase:=False).Row
        If lastRow >= found.Row Then
            Debug.Print .Rows(found.Row & ":" & lastRow).EntireRow.Delete
        End If
    End If
End With

2 个答案:

答案 0 :(得分:1)

如果还删除找到的行,则可以尝试以下操作:

Option Explicit
Public Sub DeleteRows()
    Dim lastRow As Long, found As Range
    With ThisWorkbook.Worksheets("Sheet1") '<your sheet

        Set found = .Range("B1:B" & .Cells(.Rows.Count, "B").End(xlUp).Row).Find("BEST Cards Raised:")
        If Not found Is Nothing Then
            lastRow = .Cells.Find(What:="*", _
                                  After:=.Cells(1, 1), _
                                  Lookat:=xlPart, _
                                  LookIn:=xlFormulas, _
                                  SearchOrder:=xlByRows, _
                                  SearchDirection:=xlPrevious, _
                                  MatchCase:=False).Row
            If lastRow >= found.Row Then
                .Rows(found.Row & ":" & lastRow).EntireRow.Delete
            End If
        End If
    End With
End Sub

调试后

Dim lastRow As Long, foundRow As Variant
With ThisWorkbook.Worksheets("Sheet8")
    lastRow = .Cells(.Rows.Count, "B").End(xlUp).Row
    foundRow = Application.Match("BEST Cards Raised:", .Range("B1:B" & lastRow), 0)
    If IsError(foundRow) Then Exit Sub
    If lastRow >= foundRow Then .Rows(foundRow & ":" & lastRow).EntireRow.Delete
End With

答案 1 :(得分:1)

尝试一下(代码中的注释):

Sub DeleteRows()
    Dim ws As Worksheet, lastRow As Long, i As Long, j As Long
    Set ws = ThisWorkbook.Worksheets("Sheet1")

    lastRow = ws.Cells(ws.Rows.Count, 2).End(xlUp).Row
    'determine where to start deleting rows
    For i = 1 To lastRow
        If Trim(ws.Cells(i, 2).Value) = "BEST Cards Raised:" Then Exit For
    Next
    'delete all rows from last to found row, looping backwards
    For j = lastRow To i Step -1
        ws.Rows(j).Delete
    Next
End Sub