如果单元格包含特定文本,则删除行

时间:2015-02-28 06:47:19

标签: excel vba

我想删除C列中包含“Total”和“Nett”的单元格的整行。

我尝试使用自动过滤器进行宏录制,但它只删除指定范围内的行(如果我使用其他数据集,则可能会有所不同)。

感谢您的帮助!

2 个答案:

答案 0 :(得分:0)

你走了。只需将此子文件复制并粘贴到您的文件中。要使用它,请选择要评估的SINGLE列。这将遍历已选择的每个单元格,如果它符合条件,它将删除整个行。如果您有任何疑问,请告诉我。祝好运!

Sub DeleteRows()
    'Enter the text you want to use for your criteria
    Const DELETE_CRITERIA = "Test"
    Dim myCell As Range
    Dim numRows As Long, Counter As Long, r As Long

    'Make sure that we've only selected a single column
    If Selection.Columns.Count > 1 Then
        MsgBox ("This only works for a single row or a single column. Try again.")
        Exit Sub
    End If

    numRows = Selection.Rows.Count - 1

    ReDim arrCells(0 To 1, 0 To numRows) As Variant

    'Store data in array for ease of knowing what to delete
    Counter = 0
    For Each myCell In Selection
      arrCells(0, Counter) = myCell
      arrCells(1, Counter) = myCell.Row
      Counter = Counter + 1
    Next myCell

    'Loop backwards through array and delete row as you go
    For r = numRows To 0 Step -1
        If InStr(1, UCase(arrCells(0, r)), UCase(DELETE_CRITERIA)) > 0 Then
            Rows(arrCells(1, r)).EntireRow.Delete
        End If
    Next r

End Sub

答案 1 :(得分:0)

如果单元格包含" Total"这将循环遍历C列中的单元格并删除整行。或者" Nett"。请记住,它区分大小写,所以" Nett"的第一个字母。或" Total"需要资本化才能找到它。但是,单元格中可以有其他文本。另请注意,引用不是完全限定的(即Workbook()。Worksheet()。Range())因为您没有提供工作簿或工作表名称。如果这对您不起作用,请告诉我。

Sub Delete()

Dim i as Integer

For i = Range("c" & Rows.Count).End(xlUp).Row To 1 Step -1
   If Instr(1, Cells(i, 3), "Total") <> 0 Or Instr(1, Cells(i,3),"Nett") <> 0 Then
      Cells(i,3).EntireRow.Delete
   End If
Next i

End Sub