循环浏览每个枢纽项目,并根据条件突出显示整行

时间:2018-08-02 08:04:48

标签: vba excel-vba pivot-table

在我的项目中,我需要突出显示数据透视表的某些行,其中列SubstitutionID的名称中有多个条目。

我已经reareay构建了一个函数,该函数在字典对象中返回唯一的SubstitutionID和子计数。

此外,我已经完成了透视的循环部分以突出显示透视项。它工作正常,但我需要突出显示数据透视表的整个行内容。下面的代码仅突出显示我的数据透视表中的一个单元格。

Dim dict As Object
Set dict = ITBuild.GetDuplicateEntries()

Dim pt As PivotTable, pf As PivotField, pi As PivotItem
Dim c As Variant, x As Variant

Set pt = ThisWorkbook.Sheets("Sheet3").PivotTables(1)
Set pf = pt.PivotFields("SubstitutionID")

For Each x In dict.keys
    If VBA.CInt(dict.Item(x)) > 1 Then
        For Each pi In pf.PivotItems
            If VBA.Trim(pi.Caption) = VBA.Trim(x) Then
                For Each c In pi.DataRange
                    c.Font.Color = vbRed
                Next
            End If
        Next
    End If
Next

如果有其他选择,请帮助我。

1 个答案:

答案 0 :(得分:1)

首先计算数据透视表的开始和结束列索引,然后将其与c.Row相对应。

Dim dict As Object
Set dict = ITBuild.GetDuplicateEntries()

Dim pt As PivotTable, pf As PivotField, pi As PivotItem
Dim c As Variant, x As Variant
Dim arr As Variant
Dim sCol As Long, eCol As Long

Set pt = ThisWorkbook.Sheets("Sheet3").PivotTables(1)

arr = VBA.Split(pt.TableRange2.Address, ":")
sCol = Range(arr(0)).Column
eCol = Range(arr(1)).Column

Set pf = pt.PivotFields("SubstitutionID")

For Each x In dict.keys
    If VBA.CInt(dict.Item(x)) > 1 Then
        For Each pi In pf.PivotItems
            If VBA.Trim(pi.Caption) = VBA.Trim(x) Then
                For Each c In pi.DataRange
                    Range(Cells(c.Row, sCol), Cells(c.Row, eCol)).Font.Color = vbRed
                    'c.Font.Color = vbRed
                Next
            End If
        Next
    End If
Next