使用Excel VBA根据不同的规则在其他工作簿上应用条件格式

我有一个大型数据库,我正在运行一个vba脚本,以创build许多不同的工作簿,其中只包含来自完整数据库的一些示例数据。 这是行之有效的,我正在使用一个matrix,以获得所有相关的条目,然后将整个matrix粘贴到一个新的工作簿的定义范围(而不是从一个工作表逐一复制到另一个)。 我的问题是,现在我需要添加条件格式的两个规则。

我正在寻找诸如:

Application.Worksheets("Database").Cells(k, ColumnOfInterest).Select With Selection .FormatConditions.Delete .FormulaR1C1 = "=RC[-3] =""A""" .FormatConditions.Add Type:=xlExpression, Formula1:=.FormulaR1C1Local .FormatConditions(1).Interior.ColorIndex = 6 .Formula = "" End With With Selection .FormatConditions.Delete .FormulaR1C1 = "=RC[0] =""""" .FormatConditions.Add Type:=xlExpression, Formula1:=.FormulaR1C1Local .FormatConditions(1).Interior.ColorIndex = 5 .Formula = "" End With 

换句话说,当用户在左边的第三个单元格中select“A”时,则相关单元格的颜色应该是颜色索引6,如果感兴趣的单元格是空的,则颜色代码是5.不幸的是此代码不起作用,只为条件格式创build一个单一的规则。

.FormatConditions.Delete删除以前的格式条件。 如果在第二部分中删除.FormatConditions.Delete并将.FormatConditions(1)更改为.FormatConditions(2),它应该工作:

 Application.Worksheets("Database").Cells(k, ColumnOfInterest).Select With Selection .FormatConditions.Delete .FormulaR1C1 = "=RC[-3] =""A""" .FormatConditions.Add Type:=xlExpression, Formula1:=.FormulaR1C1Local .FormatConditions(1).Interior.ColorIndex = 6 .Formula = "" .FormulaR1C1 = "=RC[0] =""""" .FormatConditions.Add Type:=xlExpression, Formula1:=.FormulaR1C1Local .FormatConditions(2).Interior.ColorIndex = 5 .Formula = "" End With