如何根据每个单元格的值和固定单元格的值有条件地格式化 VBA 中的列?



我需要为一列设置条件格式,其中每个单元格都根据从电子表格中的单元格派生的另外两个值突出显示。 这些值是日期。 这需要在 VBA 中完成(原因有很多:代码与其他软件一起使用并清除内容、将行分组在一起等)。 我在许多方法上都失败了,目前在以下方面失败了:

Sheets("Trial").Activate
With ActiveSheet.Range("E:E")
.Select
.FormatConditions.Add Type:=xlCellValue, Operator:=xlBetween, Formula1:="="
& (Range("P1").Value - 1), Formula2:="=" & (Range("P1").Value + 6)
.FormatConditions(1).Interior.Color = RGB(255, 0, 0)
End With

最终,当值介于 P1-1 和 P1+6 之间时,我需要 E 列中的单元格变为红色。 即使我提取此代码并自行运行它,我也会收到过程调用错误。 思潮?

请尝试:

Sheets("Trial").Activate
With Columns("E:E")
.FormatConditions.Add Type:=xlExpression, Formula1:="=AND(E1>=$P$1-1,E1<=$P$1+6)"
.FormatConditions(1).Interior.Color = 255
End With

如果您不想,您甚至不必使用条件格式。您可以使用 for 循环遍历 E 列中的所有值。以这个为例。

Dim TotalERows As Long
Dim EValue As Long
Dim LowerBound As Long
Dim UpperBound As Long
LowerBound = Worksheets("Sheet1").Range("P1").Value - 2
UpperBound = Worksheets("Sheet1").Range("P1").Value + 7
TotalERows = Worksheets("Sheet1").Range("E" & Rows.Count).End(xlUp).Row
For I = 1 To TotalERows
    EValue = Range("E" & I).Value
        If LowerBound < EValue And EValue < UpperBound Then
            Range("E" & I).Interior.ColorIndex = 3
        End If
Next I

最新更新