首页 > 解决方案 > 列表视图更改重复子项的颜色

问题描述

如果我有一个填充的列表视图,如果该列中已经存在子项,我将如何更改字体颜色?

任何帮助,将不胜感激。

这是我所拥有的,但它不能正常工作

Sub dupeInterpreters(lvw As ListView, iSubItemIndex As Integer)
    Dim i As Integer
    Dim dupeI As Integer

    dupeI = 0

    For i = 1 To LVIV.ListItems.Count

        If LVIV.ListItems(i).SubItems(iSubItemIndex) = LVIV.ListItems(i).ListSubItems(iSubItemIndex).Text Then 'you could also use the LIKE operator
            'LVIV.ListItems(i).Selected = True
            LVIV.ListItems(i).Bold = True
            LVIV.ListItems(i).ListSubItems(iSubItemIndex).ForeColor = &HC000&
            dupeI = dupeI + 1
            'Exit For
        End If

    Next

End Sub

没有错误,但它突出显示列表视图中的每个项目,而不仅仅是重复值

标签: excelvba

解决方案


这是另一种方法。这一个使用 Dictionary 对象来避免过度循环,并且应该更有效......

Sub dupeInterpreters(LVIV As ListView, iSubItemIndex As Integer)

    Dim dicListSubItemCount As Object
    Dim strListSubItem As String
    Dim listItemIndex As Long

    Set dicListSubItemCount = CreateObject("Scripting.Dictionary")
    dicListSubItemCount.comparemode = 1 'case-insensitive comparison

    With LVIV
        For listItemIndex = 1 To .ListItems.Count
            strListSubItem = .ListItems(listItemIndex).ListSubItems(iSubItemIndex).Text
            dicListSubItemCount(strListSubItem) = dicListSubItemCount(strListSubItem) + 1
        Next listItemIndex
        For listItemIndex = 1 To .ListItems.Count
            strListSubItem = .ListItems(listItemIndex).ListSubItems(iSubItemIndex).Text
            If dicListSubItemCount(strListSubItem) > 1 Then
                With .ListItems(listItemIndex)
                    .Bold = True
                    .ListSubItems(iSubItemIndex).ForeColor = &HC000&
                End With
            End If
        Next listItemIndex
    End With

    Me.Repaint

    Set dicListSubItemCount = Nothing

End Sub

希望这可以帮助!


推荐阅读