仅在条件格式不存在时添加条件格式

Only add conditional formatting if it does not exist yet

我将条件格式添加到 Excel 文件:

Sub Apply_Conditional_Formatting()
With Tabelle1.Range("=:48576")
    .FormatConditions.Add Type:=xlExpression, Formula1:="=$A1=$F"
    .FormatConditions(.FormatConditions.Count).Interior.Color = RGB(255, 255, 0)
End With
End Sub

此代码链接到 sheet 中的一个按钮,用户可以根据需要经常按下。
每次单击按钮时,条件格式都会添加到 sheet,这使得菜单看起来像这样:

(抱歉只有德语版)

有没有办法检查条件格式是否已经存在而不添加?

如果你只是想检查是否有 any 条件格式设置在 sheet:

With Sheet1.Cells
    If .FormatConditions.Count = 0 Then
        .FormatConditions.Add Type:=xlExpression, Formula1:="=$A1=$F"
        .FormatConditions(.FormatConditions.Count).Interior.Color = RGB(255, 255, 0)
    End If
end with

如果您想明确检查公式(因为 sheet 可能包含其他条件格式),请使用类似这样的东西

With Sheet1.Cells
    Dim fc As FormatCondition, found As Boolean
    For Each fc In .FormatConditions
        If fc.Formula1 = "=$A1=$F" Then
            found = True
            Exit For
        End If
    Next fc

    If Not found Then
        .FormatConditions.Add Type:=xlExpression, Formula1:="=$A1=$F"
        .FormatConditions(.FormatConditions.Count).Interior.Color = RGB(255, 255, 0)
    End If
End With

(将 Sheet1 替换为您要使用的 sheet)