如何使用VBA判断Excel单元格是否应用了条件格式化

8

我有一系列应用了条件格式的单元格。

目的是通过视觉方式区分具有正数、负数和无变化值的单元格。

如何使用VBA检查这些单元格是否应用了条件格式(例如由于是负数而导致单元格颜色)?


如果您能告诉我如何测试单元格中样式的存在(例如当它有多个样式时,比如“逗号”和“好”),那么我会花时间回答所有未回复的问题。是否有一种过滤器可以应用于我的账户,以查看所有这些问题? - yoshiserry
3个回答

3

检查Count是否为零:

Sub dural()
    MsgBox ActiveCell.FormatConditions.Count
End Sub

2

您可以使用Range.DisplayFormat来检查是否应用了条件格式。 将一些数据放入A列,然后使用以下代码示例:

Private Sub TestConditionalFormat()
Range("A:A").FormatConditions.AddUniqueValues
Range("A:A").FormatConditions(1).DupeUnique = xlDuplicate
Range("A:A").FormatConditions(1).Interior.Color = 13551615


Dim rCell       As Range
Dim i           As Long
For Each rCell In Range(Range("A1"), Range("A1").End(xlDown))
If rCell.DisplayFormat.Interior.Color = 13551615 Then
i = i + 1
End If
Next
MsgBox i & " :Cells Highlights for Duplicates."
End Sub

Range.DisplayFormat获胜。我希望我能将其标记为正确答案。 - nollaf126

1

使用VBA检查单元格是否有条件格式,请使用以下代码:

Dim check As Range
Dim condition As FormatCondition
Set check = ThisWorkbook.ActiveSheet.Cells.Range("A1") 'this is the cell I want to check
Set condition = check.FormatConditions(1) 'this will grab the first conditional format
condition. 'an autolist of methods and properties will pop up and 
           'you can see all the things you can check here
'insert the rest of your checking code here

您可以使用上面的代码部分,配合 for each 循环来检查特定范围内的所有条件。

谢谢。你是说必须逐个检查每种条件格式吗?能否只检查任何一种?然后如果有,再测试哪一个? - yoshiserry
编程营员--如果您不知道要测试哪个数字条件格式怎么办?例如,如果我需要知道单元格中的颜色,我可以编写c = activecell.interior.color来查找,然后在其他地方进行测试。如何测试条件格式,即红色或绿色或应用于单元格的颜色是什么? - yoshiserry
@yoshiserry 在条件格式方面,您将不得不逐个测试并确切知道您要查找的内容。如果您想知道什么颜色被应用于条件格式,请尝试使用我的代码,并使用condition.Interior.Color进行测试。如果您提供了一个非常具体的示例,我会尝试为您测试一些代码。 - CodeCamper

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接