Excel VBA突出显示不包含单词列表中文本的范围中的单元格

时间:2015-06-10 21:52:05

标签: excel vba excel-vba

我正在尝试搜索B列并突出显示包含文字除了单词Flyer,Bulk Clearance,Eat In Season,Line Drive,Market Special,Push Item和Weekender之外的所有单元格。我故意从第三行开始。

下面的代码仅适用于一个单词(Flyer),但我希望宏能够将单元格中的文本与上面提到的单词列表进行比较,并突出显示文本是否与在列表中。

Sub Orange()
Dim LR As Long, i As Long

LR = ActiveSheet.Range("B" & Rows.Count).End(xlUp).Row
For i = 3 To LR
    With Range("B" & i)
        If .Value <> "Flyer" Then .Cells.Interior.ColorIndex = 45
    End With
Next i

MsgBox "The orange are not valid values."
End Sub 

3 个答案:

答案 0 :(得分:1)

一种简单的方法是创建一个存储有效值的字典,然后检查它们是否在字典中:

'Requires reference to Microsoft Scripting Runtime.
Sub Orange()
    Dim temp() As String

    temp = Split("Flyer,Bulk Clearance,Eat In Season,Line Drive,Market Special,Push Item,Weekender", ",")

    Dim items As New Dictionary, item As Variant
    For Each item In temp
        items.Add item, item
    Next item

    Dim LR As Long, i As Long

    LR = ActiveSheet.Range("B" & Rows.Count).End(xlUp).row
    For i = 3 To LR
        With Range("B" & i)
            If Not items.Exists(.Value) Then .Cells.Interior.ColorIndex = 45
        End With
    Next i

    MsgBox "The orange are not valid values."
End Sub

答案 1 :(得分:0)

也许这个??

Sub HighlightFound()
Dim FoundCell As Range, MyArr As Variant, X As Long, FindRange As Range
MyArr = Array("Flyer", "Bulk Clearance", "Eat In Season", "Line Drive", "Market Special", "Push Item", "Weekender")
Set FindRange = Range("B3:B" & Range("B" & Rows.Count).End(xlUp).Row)
For X = LBound(MyArr) To UBound(MyArr)
    Set FoundCell = FindRange.Find(MyArr(X))
    Do Until FoundCell Is Nothing
        If FoundCell.Row > FindRange.FindNext(after:=FoundCell).Row Then
            Exit Do
        Else
            FoundCell.Interior.ColorIndex = 45
            Set FoundCell = FindRange.FindNext(after:=FoundCell)
        End If
    Loop
Next
End Sub

答案 2 :(得分:0)

只需使用条件格式规则。 主页&gt;条件格式&gt; <高亮显示单元格规则>包含

的文字

然后对每个单词都有一个规则: - 手动输入单词 - 或使用单元格引用并将其指向应该查看的单元格