比较两列并突出显示单元格

时间:2019-03-18 07:54:25

标签: excel vba

我试图编写一个VBA来比较AB和AE列,并检查AB列是否包含“ High”值,则相应的AE列不应包含小于当前日期的日期-10个月,否则单元格应以红色突出显示。我尝试了以下代码,但突出显示了所有日期值。

Dim High As Range
Dim StartDate As Date
For Each High In Range("AB:AB")
    If High.Value = "High" Then
        If Not IsDate(Range("AE" & High.Row) = StartDate - 300) Then
            Range("AE" & High.Row).Interior.Color = 255
        End If
    End If
Next High

2 个答案:

答案 0 :(得分:0)

就像Pᴇʜ已经提到的那样,您可以通过使用条件格式来完成此操作。但是,如果您要一次为单元格上色,请静态地将代码编辑为以下内容:

Dim High As Range
Dim StartDate As Date

StartDate = Date

With Workbooks(REF).Sheets(REF) 'Add correct references

LRow = .Cells(.Rows.Count, "AB").End(xlUp).Row
For Each High In .Range("AB2:AB" & LRow) 'Assuming you have a header row
    If High.Value = "High" Then
        If IsDate(.Range("AE" & High.Row)) = False Then 
            .Range("AE" & High.Row).Interior.Color = vbRed
        Else
            If DateValue(.Range("AE" & High.Row)) < StartDate -300  Then .Range("AE" & High.Row).Interior.Color = vbRed
        End If
    End If
Next High

End With

答案 1 :(得分:0)

代码使用OP“ Not IsDate(),使用And / Or删除多余的IF,使用Offset将第二个单元格分配为变量,并使用单元格变量和.address同时为两个单元格着色。 / p>

Dim sDate作为日期,cel作为范围,cel2作为范围 sDate =日期

With ThisWorkbook.Sheets("Sheet1")
    'loop through each cell in range, does not use lRow variable
    For Each cel In .Range("A2:A" & Cells(Rows.Count, "A").End(xlUp).Row)
        Set cel2 = cel.Offset(, 4) 'Set the second cell variable to column E using offset

        'Use And/Or in the IF statement to test the values in the ranges
        If cel.Value = "High" And (Not IsDate(cel2) Or cel2 < sDate - 300) Then
            'Set both cells color at the same time using the cell address for both variables
            Range(cel.Address & "," & cel2.Address).Interior.Color = vbRed
        End If
    Next cel
End With