如果找到内容,请删除整行

时间:2013-12-17 15:41:48

标签: excel vba excel-vba

如果单元格以“Joe Smith”或“Jim Bob”文本开头,我想删除整行。这是我从另一个问题获得的代码,但需要修改:

Sub SimpleDeletingMechanism()

    Dim c As Range

    ' loop through all cells in range A1:A + last userd Row in column A
    For Each c In Range("A1:A" & Range("A" & Rows.Count).End(xlUp).Row)

        ' when Joe Smith is found in cell's content
        If InStr(1, c.Text, "Joe Smith", vbTextCompare) > 0 Then

            ' delete that row


        ' when Jim Bob is found in cell's content
        ElseIf InStr(1, c, "Jim Bob", vbTextCompare) > 0 Then

            ' delete that row

        End If
    Next

End Sub

如果找到其中一个名字,有人可以帮我填补删除行的空白吗?

1 个答案:

答案 0 :(得分:4)

每当您从集合中删除对象时,您必须向后迭代,否则,当集合被重新编入索引时,您最终会“跳过”某些元素。

Sub SimpleDeletingMechanism()
    Dim rng as Range
    Dim c As Range
    Dim i as Long 

    Set rng = Range("A1:A" & Range("A" & Rows.Count).End(xlUp).Row)

    For i = rng.Rows.Count to 1 Step -1 '// Iterate BACKWARDS over the collection
        Set c = rng.Cells(i,1)
        ' when Joe Smith is found in cell's content
        If InStr(1, c.Text, "Joe Smith", vbTextCompare) > 0 Then

            c.EntireRow.Delete


        ' when Jim Bob is found in cell's content
        ElseIf InStr(1, c, "Jim Bob", vbTextCompare) > 0 Then

            c.EntireRow.Delete

        End If
    Next

End Sub