如果列中不包含特定值/文本,则突出显示该单元格

时间:2019-11-21 09:51:42

标签: excel vba

我还是Macro的新手,并希望在以下条件下完美运行以下代码:

1)此vba从E2列开始运行,直到单元格的最后一个条目,即Vba仅在具有值/条目的单元格上运行,而不在空白单元格上运行。

2)如果该特定单元格包含其他单词,则以黄色突出显示该单元格。

下面是我尝试的代码:

'Highlight cell in Column E if it does not contain "USD"
    If WorksheetFunction.IsText(Range("E2:E").Value) Then
    With Range("E2:E")
        .FormatConditions.Delete
        .FormatConditions.Add Type:=xlExpression, Operator:=xlNotEqual, _
            Formula1:="=E2:E<>""USD"""
        With .FormatConditions(1).Interior
            .Color = vbYellow
        End With
    End With
    End If

面临的问题:

1)不满足第一个条件。

2)只有添加特定的单元格范围,我才能使第二个条件起作用,例如:

'Highlight cell in Column E if it does not contain "USD"
    If WorksheetFunction.IsText(Range("E2:E").Value) Then
    With Range("E2:**E100**")
        .FormatConditions.Delete
        .FormatConditions.Add Type:=xlExpression, Operator:=xlNotEqual, _
            Formula1:="=E2:**E100**<>""USD"""
        With .FormatConditions(1).Interior
            .Color = vbYellow
        End With
    End With
    End If

在此方面需要帮助。谢谢。

1 个答案:

答案 0 :(得分:2)

遍历范围并比较单元格文本与您的条件比较简单:

Sub CheckCellAndHighlight()
Dim CheckCell As range, CheckRange As range

Set CheckRange = range(Cells(2, 5), Cells(Rows.Count, 5).End(xlUp)) ' Set the range you need to look through

For Each CheckCell In CheckRange
    If Not UCase(CheckCell.Text) = "USD" Then ' do not need to check whether the cell's value is text, just check whether it meets you particular condition
        CheckCell.Interior.Color = vbYellow ' color it if it meets the condition
    Else
        CheckCell.Interior.Color = xlNone
    End If
Next

End Sub

Not CheckCell.Text = "USD"的含义与CheckCell.Text <> "USD"相同。

更新

根据注释,添加了两项检查-一种用于检查文本的大小写,因为“ usd”不等于“ USD”,第二种-清除颜色,因为该单元格以前可能已经着色。

相关问题