[英]In Excel how to replace cell interior color with two conditions
在我的 Excel 工作表中,第一個條件是根據行和列的文本匹配用藍色突出顯示相交的單元格。
第二個條件:如果單元格值(日期格式)小於今天的日期,則以藍色突出顯示的單元格值必須變為紅色。
我能夠滿足第一個條件,但未能滿足第二個條件。
Excel 數據如下所示:
第一個條件:
第二個條件:我面臨的問題是獲得紅色內飾
我正在嘗試使用 VBA 代碼,如下所示:
Sub RunCompare() Dim ws As Worksheet Set ws = ActiveSheet Dim cols As Range, rws As Range Dim lastRow As Integer: lastRow = ws.UsedRange.Rows.Count Dim lastColumn As Integer: lastColumn = ws.UsedRange.Columns.Count For Each cols In ws.Range(ws.Cells(4, 1), ws.Cells(4, lastColumn)) If cols.Value <> vbNullString Then For Each rws In ws.Range("A1:A" & lastRow) 'first condition statement If (rws.Value = cols.Value) Then ws.Cells(rws.Row, cols.Column).Interior.Color = RGB(15, 219, 241) End If 'second condition statement If (rws.Value = cols.Value) < Date Then ws.Cells(rws.Row, cols.Column).Interior.Color = RGB(255, 0, 0) End If Next End If Next End Sub
這可以通過條件格式輕松完成。
根據這些公式添加兩條規則:
紅色: =AND($A3=B$1,B3<>"",B3<TODAY())
。
藍色: =AND($A3=B$1,B3<>"")
如果您真的想保留當前的 VBA,您可以更改
If (rws.Value = cols.Value) < Date Then
至
If (rws.Value = cols.Value) And (ws.Cells(rws.Row, cols.Column).Value < Date) Then
或者您可以進一步簡化,通過在現有的 BLUE 條件檢查中移動 RED 條件( rws.Value = cols.Value
對於紅色和藍色都必須為真。)
If rws.Value = cols.Value Then
With ws.Cells(rws.Row, cols.Column)
If .Value < Date Then
.Interior.Color = RGB(255, 0, 0) ' RED
Else
.Interior.Color = RGB(15, 219, 241) ' BLUE
End If
End With
End If
這個解決方案適合您嗎?
Dim ws As Worksheet
Dim col As Integer
Dim row As Integer
Dim lastRow As Integer
Dim lastCol As Integer
Dim OK As Boolean
Set ws = ActiveSheet
lastRow = ws.UsedRange.Rows.Count
lastCol = ws.UsedRange.Columns.Count
For col = 1 To lastCol
For row = 2 To lastRow
If ws.Cells(row, 1).Value = ws.Cells(1, col).Value Then
If ws.Cells(row, col) < Date Then
ws.Cells(row, col).Interior.Color = RGB(255, 0, 0)
Else
ws.Cells(row, col).Interior.Color = RGB(15, 219, 241)
End If
End If
Next
Next
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.