簡體   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