excel教程:Excel 2007新知:在VBA中使用条件格式的举例

  自从我收到些有关“如何在VBA中使用新条件格式”询问我就想提供给大家些简单举例在我们Excel开发团队(Team)中有条法则:当我们增加任何新功能时我们必须确定它们在被时能和在用户界面中工作样好Excel 12对象模型支持所有出现在用户界面中条件格式功能包括增加、编辑和s删除规则或者更改规则优先级

  在旧版本Excel中写过和条件格式相关VBA代码人会知道条件格式集不能使用Range对象让我通过运行些简单举例来展示如何使用条件格式集中新功能

  增加个规则:

  Excel 12中条件格式规则(Data bars, Color Scales, Icon Sets, Top n等待)可以在条件格式集中使用Add <对象名>思路方法来创建比如创建个data bar:

  Range("A1:A5").FormatConditions.AddDatabar

  编辑现有规则:

  编辑规则是通过定位条件格式集索引号并修改其属性比如更改data bar颜色:

  Range("A1:A5").FormatConditions(1).BarColor.ColorIndex = 3

  在这里数字1表示区域中个规则

  编辑规则优先级:

  在Excel 12里规则优先级这个概念表示支持在个区域建立多重条件优先级决定规则执行次序在对象模型里我们同样可以使用条件格式对象优先级属性此属性在工作表级被追踪比如检验某条规则优先级:

  Range("A1:A5").FormatConditions(1).Priority

  将某规则降至最低优先级:

  Range("A1:A5").FormatConditions(1).SetLastPriority

  分配项指定优先级:

  Range("A1:A5").FormatConditions(1).Priority = 3

  注意如果你只有3条规则那么设置优先级为3和设置优先级为最低效果是

  删除规则:

  你可以根据索引号并使用Delete思路方法来删除个指定规则:

  Range("A1:A5").FormatConditions(1).Delete

  也可以将Delete思路方法作用于条件格式集来删除指定区域中所有规则:

  Range("A1:A5").FormatConditions.Delete

  下面是另个举例假设你想用VBA来把单元格区域A1-A10中数值最高5%突现并填充为红色以下是相关代码:

Sub Top5Percent
'Adding the Top10 rule to the range
Range("A1:A10").FormatConditions.AddTop10
'Assign the rank of the condition to 5
Range("A1:A10").FormatConditions(1).Rank = 5
‘Set the Percent property true. It is false by default.
Range("A1:A10").FormatConditions(1).Percent = True
'Set the color to a red fill
Range("A1:A10").FormatConditions(1).Interior.ColorIndex = 3
End Sub


  希望这些对您有所帮助

Tags:  excel表格 excel2007 excel2003 excel教程

延伸阅读

最新评论

发表评论