[英]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.