Warning: file_get_contents(/data/phpspider/zhask/data//catemap/0/vba/15.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
如何根据每个单元格的值和固定单元格的值在VBA中有条件地格式化列?_Vba_Date_Excel_Conditional Formatting - Fatal编程技术网

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

如何根据每个单元格的值和固定单元格的值在VBA中有条件地格式化列?,vba,date,excel,conditional-formatting,Vba,Date,Excel,Conditional Formatting,我需要为列设置条件格式,其中每个单元格根据从电子表格中的单元格派生的两个其他值高亮显示。这些值是日期。这需要在VBA中完成,原因有很多:代码与其他软件一起工作,清除内容,将行分组在一起,等等。。我在许多方法上都失败了,目前在以下方面都失败了: Sheets("Trial").Activate With ActiveSheet.Range("E:E") .Select .FormatConditions.Add Type:=xlCellValue, Operator:=xlBetween, For

我需要为列设置条件格式,其中每个单元格根据从电子表格中的单元格派生的两个其他值高亮显示。这些值是日期。这需要在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

这确实是一个问题。我只是觉得如果有必要的话,这个方法可能是一个有趣的选择。我仍然得到一个错误。我要补充的是,这些值是日期,将对问题进行编辑以反映这一点。我曾尝试使用日期变量,并将它们嵌入到上面列出的公式中,但没有成功。