激活工作表时将重新创建条件格式 - Excel VBA

时间:2013-04-19 13:41:31

标签: vba excel-vba excel-2010 conditional-formatting excel

我在excel上的工作表上有代码,每次激活工作表时都会运行 Private Sub Worksheet_Activate()。我有条件格式的代码,但每次激活worksheeet时,它会一次又一次地重新创建相同的格式。我如何编码,如果条件格式已经存在,什么都不做?

任何帮助将不胜感激!

代码:

Private Sub Workbook_Open()

'Comparison w. Agg Loss Code: Conditional Formatting

Dim wb As Workbook
Dim LastRowAgg As Long
Dim LastColumnAgg As Long

Set wb = ActiveWorkbook


With wb.Sheets("Comparison w. Agg Loss")

    .Select
    'Format to 3 decimal places
    LastRowAgg = .Cells(Rows.Count, 1).End(xlUp).Row
    LastColumnAgg = .Cells(4, Columns.Count).End(xlToLeft).Column
    .Range(.Cells(5, 2), .Cells(LastRowAgg, LastColumnAgg)).NumberFormat = "0.000"

    'Formula for conditional formatting
    .Range(.Cells(5, 2), .Cells(LastRowAgg, LastColumnAgg)).Select
    Selection.FormatConditions.Add Type:=xlExpression, Formula1:= _
        "=AND((ABS('Input Correlation'!B5:AT" & LastRowAgg & "-'Aggregate Loss Correlation'!B5:AT" & LastRowAgg & ")/'Input Correlation'!B5:AT" & LastRowAgg & ")>=(1/3),B5:AT" & LastRowAgg & "<>"" "")"
    Selection.FormatConditions(Selection.FormatConditions.Count).SetFirstPriority
        With Selection.FormatConditions(1).Interior
            .PatternColorIndex = xlAutomatic
            .Color = 255
            .TintAndShade = 0
        End With
    Selection.FormatConditions(1).StopIfTrue = False

end with

end sub

1 个答案:

答案 0 :(得分:0)

只需测试FormatConditions.Count是否大于0。