如何获取FormatCondition对象

时间:2019-04-17 07:35:53

标签: excel vba

我想读出条件格式为特定单元格设置的颜色。

示例,注释和下面我尝试过的代码。注意:选择只是包含条件格式的单元格。

如何获得对FormatCondition对象的引用?我想念/看不到什么?最后一行错误...

Sub FC_Test()
Dim fc As FormatConditions
Dim fco As Object
Dim c As Object
Dim myRng As Range
Set myRng = Selection 'Any cell with a conditional format

Debug.Print "FC Count: " & myRng.Resize(1, 1).FormatConditions.Count

'Finds all FC on the sheet
Set fc = Cells.FormatConditions
Debug.Print TypeName(fc) 'Returns: FormatConditions

'Finds first applied format condition...
'...oddly this is not a FormatCondition (member of hte FC collection),
' but the name of the type of format condition applied.. i.e. "ColorScale", etc.
Set c = Cells.FormatConditions(1)
Debug.Print TypeName(c) 'Returns: ColorScale

'Finds FC in selected range.
Set fc = myRng.Resize(1, 1).FormatConditions
Debug.Print TypeName(fc) 'Returns: FormatConditions
Debug.Print TypeName(fc.Item(1)) 'Returns: ColorScale
Set fco = fc(1)
Debug.Print TypeName(fco) 'Returns: ColorScale

Set fco = Nothing
For Each fco In fc
    Debug.Print TypeName(fco) 'Returns: ColorScale
Next fco

Dim fcs As FormatCondition
Set fcs = myRng.Resize(1, 1).FormatConditions(1) 'Type Mismatch:13

End Sub

2 个答案:

答案 0 :(得分:1)

FormatConditions集合可以包含不同类型的对象:FormatConditionDatabarColorScaleIconSetCondition,...。

这些是具有不同属性的不同类-对象的类型取决于条件格式设置规则的类型。

这意味着当应用不同的规则(例如色阶)时,不可能获得FormatCondition对象。 要读取单元格的颜色(无论是常规格式还是条件格式),都可以使用Range.DisplayFormat

答案 1 :(得分:0)

FormatConditions object

With myRng.FormatConditions(1)
    .Interior.PatternColorIndex = xlAutomatic
    .Interior.ColorIndex = 19
    .Font.ColorIndex = 26
End With