繁体   English   中英

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

[英]Highlight cell in a column if it does not contain specific value/text

我仍然是 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

请在这方面需要帮助。 谢谢。

循环遍历范围并将单元格的文本与您的条件进行比较更简单:

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”,第二项 - 清除颜色,因为单元格之前可能已着色。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM