使用VBA打开和关闭条件格式

时间:2016-08-18 11:28:37

标签: excel vba excel-vba

如何使用VBA打开和关闭条件格式?

我有一个范围C3:AD46。我有两种条件格式。

enter image description here enter image description here

我想使用宏来打开/关闭第一种格式。第二种格式可以一直保持启用状态。

感谢。

2 个答案:

答案 0 :(得分:1)

您可以使用一种方法,而不是通过VBA代码复制条件格式,而是使用条件格式屏幕中的“如果为真,请停止”功能。

这个想法是,您的VBA代码可以更改单个单元格的值,然后新的条件格式设置规则将检查该单元格的值。如果为true,则条件格式将不应用任何新的格式更改,而是选择“停止,如果为True”复选框,则新规则将仅阻止excel检查以下规则(即,您希望由VBA代码控制的规则) 。这实际上意味着隐藏的单元格值就像一个布尔“开关”,它控制是否运行条件格式规则。

答案 1 :(得分:0)

对于第一种格式,我能够拼凑出以下内容:

Private Sub CheckBox1_Click()
   Dim rngMyRange As Range

   Set rngMyRange = ActiveWorkbook.Worksheets("tim-vgr_hgn").Range("C3:AO46")  'Set your range here

    If rngMyRange.FormatConditions.Count = 0 Then  'Set Conditional Formats
      With rngMyRange
            .FormatConditions.AddColorScale ColorScaleType:=3

            ' Format the first color as green
            .FormatConditions(1).ColorScaleCriteria(1).Type = xlConditionValueNumber
            .FormatConditions(1).ColorScaleCriteria(1).Value = 0
            .FormatConditions(1).ColorScaleCriteria(1).FormatColor.Color = RGB(0, 255, 0)

            ' Format the second color as yellow
            .FormatConditions(1).ColorScaleCriteria(2).Type = xlConditionValueNumber
            .FormatConditions(1).ColorScaleCriteria(2).Value = 120
            .FormatConditions(1).ColorScaleCriteria(2).FormatColor.Color = RGB(255, 255, 0)

            ' Format the third color as red
            .FormatConditions(1).ColorScaleCriteria(3).Type = xlConditionValueNumber
            .FormatConditions(1).ColorScaleCriteria(3).Value = 7200
            .FormatConditions(1).ColorScaleCriteria(3).FormatColor.Color = RGB(255, 0, 0)

      End With

    Else    'Clear Conditional Formats

      rngMyRange.FormatConditions.Delete

    End If
End Sub

但是,如何重新创建第二种格式?

[编辑]

我将为第二种格式开始一个新问题。