首页 > 解决方案 > 获取条件格式的单元格(DupeUnique = xlDuplicate)

问题描述

我使用以下方法突出显示选择中的所有重复单元格:

Selection.FormatConditions.AddUniqueValues
Selection.FormatConditions(Selection.FormatConditions.Count).SetFirstPriority
Selection.FormatConditions(1).DupeUnique = xlDuplicate
With Selection.FormatConditions(1).Font
    .Color = -16383844
    .TintAndShade = 0
End With
With Selection.FormatConditions(1).Interior
    .PatternColorIndex = xlAutomatic
    .Color = 13551615
    .TintAndShade = 0
End With

现在我不仅想突出显示这些单元格,而且我想获得一个包含所有受影响单元格的数组。我尝试遍历我的选择并检查 Interior 属性,但这需要很长时间。我正在寻找更快的方法。

标签: excelvba

解决方案


一个函数,返回 Excel 选择中所有值的列表(集合),对应于这个条件:

If myCell.DisplayFormat.Interior.Color = myColor Then

会很有用:

Sub TestMe()

    '...OP Code
        .TintAndShade = 0
    End With

    Dim unique As Collection
    Set unique = ResultList(Selection)
    If unique.Count > 1 Then Debug.Print unique.Item(2)

End Sub

Public Function ResultList(selectedRange As Range, _
            Optional myColor As Long = 13551615) As Collection

    Dim myCell As Range
    Dim myResultList As New Collection

    For Each myCell In selectedRange
        If myCell.DisplayFormat.Interior.Color = myColor Then
            myResultList.Add myCell.Value2
        End If
    Next myCell
    Set ResultList = myResultList

End Function

因此,Selection可以避免使用它,并且可以进一步使用它。


推荐阅读