VBA循环2个范围,并将IF语句应用于这两个范围的值

我是相对较新的Excel VBA,我想写一个代码,检查一些值,并突出显示与IF语句相匹配的值。

在一个表中,我需要遍历两个不同范围内的所有值,其中一个范围的值是date,另一个值是几个不同的string,并突出显示(橙色)对应于以下要求的行: )第一范围值> =到今天的date和(2)第二范围值=“样本收据”。 我还需要遍历date范围的所有值,并突出显示(黄色)与当天date相对应的行。 所有其他不符合这些要求的行都需要以浅蓝色突出显示。

我的第一个代码(如下所示)工作,但它突出了第二个范围的所有值=“样本收据”。

Dim LastRow As Long Dim cell As Range Dim cell2 As Range Worksheets("Sheet3").Activate With ActiveSheet LastRow = .Cells(.Rows.Count, "A").End(xlUp).Row For Each cell In Range("K3:K" & LastRow) If cell.Value >= Date Then cell.Range("A1:K1").Offset(0, -10).Interior.ColorIndex = 6 ElseIf cell.Value >= Date - 7 Then For Each cell2 In Range("H3:H" & LastRow) If cell2.Value = "Sample Receipt" Then cell2.Range("A1:K1").Offset(0, -7).Interior.ColorIndex = 45 Else cell2.Range("A1:K1").Offset(0, -7).Interior.Color = RGB(220, 230, 242) End If Next Else cell.Range("A1:K1").Offset(0, -10).Interior.Color = RGB(220, 230, 242) End If Next End With 

我不能想到另一种方式来设置For循环,以允许我需要和我已经环顾四周。

像这样的东西:

 Sub TT() Dim sht As Worksheet Dim LastRow As Long Dim cell As Range Dim dt, txt Dim clr As Long Set sht = Worksheets("Sheet3") LastRow = sht.Cells(.Rows.Count, "A").End(xlUp).Row For Each cell In sht.Range("K3:K" & LastRow).Cells dt = cell.Value txt = cell.Offset(0, -3).Value 'don't follow your original logic so ' this is just an example.... If dt >= Date And txt = "Sample Receipt" Then clr = vbRed ElseIf dt >= Date - 7 Then clr = vbYellow Else clr = RGB(220, 230, 242) 'default color End If cell.EntireRow.Cells(1).Color = clr Next End Sub