
[英]VBA How do I conditionally format a range of cells based on the value of one cell in that range?
[英]How do I conditionally format a column in VBA based on each cell's value and a fixed cell's value?
我需要为一列设置条件格式,其中基于从电子表格中的单元格派生的其他两个值来突出显示每个单元格。 值是日期。 这需要在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
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.