条件格式定义范围

时间:2017-05-16 05:58:20

标签: excel vba

我有以下代码:

Sub ConditionalFormattingNamedRange()                                     
Dim x As Range, Cell As Range

Set x = Range("AALB_Exposure")

For Each Cell In x
    If Cell.Value > Sheets("Overview").Range("E4").Value Then
        Cell.Interior.Color = RGB(0, 255, 0)
    End If
Next 
End Sub

背景信息:此公式使我定义的范围“AALB_Exposure”中的值变为彩色,如果它们大于“概览”表单上的单元格E4。单元格E4的值是另外两个单元格的结果。有时其中一个细胞会发生变化。我有超过20个定义的范围,例如“AALB_Exposure”,所以我更喜欢使用模块。

问题:此模块使所有值都着色。有时在“AALB_Exposure”中有一些空白单元格。我想看到这不会发生。这可能吗? 此外,此模块是静态的,在我调整E4时不会修改定义范围内的单元格颜色。这只在我运行模块后才会发生。是否可以确保根据E4值的变化立即调整细胞的颜色。

谢谢!

-----编辑------

在布鲁斯韦恩的出色建议之后,我改变了我的代码。

Private Sub Workbook_SheetCalculate(ByVal Target As Range, ByVal Sh As Worksheet) 
If Target.Address = "$A$9" Then                    
Application.ScreenUpdating = False    
Dim x As Range, Cell As Range  
Set x = Sh.Range("P1:P150,AD1:AD150,AR1:AR150,BF1:BF150,BT1:BT150,CH1:CH150,CV1:CV150,DJ1:DJ150,DX1:DX150,EL1:EL150")                                                 
For Each Cell In x
If Cell.Value > Sh.Range("A9").Value And Cell.Value <> "" Then
    Cell.Interior.Color = RGB(0, 255, 0)
End If
Next
End If  
Application.ScreenUpdating = True 

结束子

由于每个工作表的命名范围始终相同,因此以这种方式解决问题可能更好吗?因此,我更改了位于Overview页面上的Cell E4,以便为每个工作表始终位于相同位置的单元格。 但是,这个新模块是否正确?

1 个答案:

答案 0 :(得分:0)

如果您希望在更改Private Sub Worksheet_Change(ByVal Target As Range) If Target.Address = "$E$4" Then Application.ScreenUpdating = False Dim x As Range, Cell As Range Set x = Range("AALB_Exposure") For Each Cell In x If Cell.Value > Sheets("Overview").Range("E4").Value And Cell.Value <> "" Then ' added `AND` part to check if cell is not blank Cell.Interior.Color = RGB(0, 255, 0) End If Next End If Application.ScreenUpdating = True End Sub 时运行此项,则需要将其放在工作表更改事件中:

id      position      date
1          a          2012 01 12
2          a          2012 01 22
3          a          2012 01 22
1          b          2012 02 13
1          c          2012 02 22
2          b          2012 01 23

将其放在要运行它的工作表的工作表模块中。在添加颜色之前,它还会检查单元格是否为空白。