如何选择不包含某个单词的单元格

时间:2017-10-03 12:00:58

标签: excel vba excel-vba

我有一个Excel表格,其中C列的一些单元格包含单词" Rinse" (其他单元格有各种其他内容)。

使用VBA代码,这里我将如何选择包含单词" Rinse"在C列中 - 此代码工作正常。

For i = 3 To 300
    If Cells(i, 3).Value = "Rinse" Then
        Rows(i).Select
        Selection.FormatConditions.Delete
    End If
Next

但是,我想做的恰恰相反,即选择所有不包含单词&#34的行; Rinse"在C栏。我尝试了以下方法,但它没有用。

For i = 3 To 300
    If Cells(i, 3).Value = Not "Rinse" Then
        Rows(i).Select
        Selection.FormatConditions.Delete
    End If
Next

我该如何完成这项工作?

6 个答案:

答案 0 :(得分:2)

使用Instr功能,如下所示:

If Instr(Cells(i, 3).Value, "Rinse") = 0 Then

答案 1 :(得分:2)

Like运算符在这里很有用:

If Not Cells(i, 3).Value Like "*Rinse*" Then

如果"冲洗"可以在单元格值的任何位置找到

答案 2 :(得分:2)

更改代码的这一行(<>不等于)

 If Cells(i, 3).Value <> "Rinse" Then

答案 3 :(得分:2)

您可以过滤掉漂洗值,然后选择可见的细胞 可能比看每个单元格更快。

Public Sub Test()

    Dim lRow As Long

    With ThisWorkbook.Worksheets("Sheet1")
        lRow = .Cells(.Rows.Count, 3).End(xlUp).Row
        With .Range(.Cells(1, 3), .Cells(lRow, 3))
            .AutoFilter Field:=1, Criteria1:="<>*Rinse*"
            'Can replace Select in next row with .FormatConditions.Delete
            .SpecialCells(xlCellTypeVisible).Select
        End With
        .ShowAllData
    End With

End Sub

答案 4 :(得分:1)

此代码的优势在于速度。通过仅为每行引用一次表单,仅为结果引用一次,并且仅格式化使用的范围列而不是整行来实现加速。

Private Sub SelectNonContiguousRange()

    Dim RngAddress() As String
    Dim i As Long
    Dim R As Long

    ReDim RngAddress(300)                   ' this number should be
    With ActiveSheet
        For R = 3 To 300                    ' equal to this number
            ' use = (equal) or <> (unequal) as required:
            If .Cells(R, "C").Value <> "Rinse" Then
'            If .Cells(R, "C").Value = "Rinse" Then
                RngAddress(i) = .Range(.Cells(R, "A"), _
                                       .Cells(R, .UsedRange.Columns.Count)).Address
                i = i + 1
            End If
        Next R
        ReDim Preserve RngAddress(i - 1)
        .Range(Join(RngAddress, ",")).FormatConditions.Delete
    End With
End Sub

顺便说一下,您可以使用此代码的变体来同时选择多行(就像您可以使用Ctl + Click一样),例如包含“Rinse”一词的所有行。

答案 5 :(得分:0)

@Renee - 更改if条件行,如下所示。

For i = 3 To 300
    If Cells(i, 3).Value <> "Rinse" Then
        Rows(i).Select
        Selection.FormatConditions.Delete
    End If
Next