如何检查数据透视表中的数据是否在另一个公式中使用

时间:2019-05-01 16:18:32

标签: excel vba pivot-table

我在公式中使用数据透视表中的数据。数据透视表中有很多数据,我需要检查公式中已经使用了哪些数据。

我已经使用了这段代码来标记已使用的数据透视表数据,但是没有用。

Cells(24, "g").Precedents.Interior.ColorIndex = 5

enter image description here

1 个答案:

答案 0 :(得分:1)

您已经发现,具有Range.Precedents公式的单元格的GETPIVOTDATA仅指向数据透视表的第一个单元格。因此,您不能使用先例来识别数据透视表中已引用的单元格。

我的代码执行以下操作:

  • 每个数据透视表的数据范围单元格构建 = GETPIVOTDATA()公式字符串
  • 将这些可能公式收集到数组中
  • 比较每个使用公式,例如G。此数组在G1:G500范围内
  • 如果找到该公式,则相应的枢轴单元标记为黄色
    Private Sub EveryPossibleGETPIVOTDATAformula()
        Dim pt As PivotTable
        Dim pi As PivotItem
        Dim pc As PivotCell
        Dim c As Range
        Dim i As Long, j As Long
        Dim PossibleFormulas() As String

        Set pt = ActiveSheet.PivotTables(1)

        ReDim PossibleFormulas( _
            1 To _
            pt.PivotRowAxis.PivotLines.Count * _
            pt.PivotColumnAxis.PivotLines.Count)

        i = 1
        For Each c In pt.DataBodyRange.Cells
            Set pc = c.PivotCell
            PossibleFormulas(i) = _
                "=GETPIVOTDATA(""" & _
                pc.DataField.SourceName & """," & _
                pt.TableRange1.Cells(1).Address
            For Each pi In pc.RowItems
                PossibleFormulas(i) = PossibleFormulas(i) & _
                    ",""" & pi.Parent.Name & _
                    """,""" & pi.Value & """"
            Next pi
            For Each pi In pc.ColumnItems
                PossibleFormulas(i) = PossibleFormulas(i) & _
                    ",""" & pi.Parent.Name & _
                    """,""" & pi.Value & """"
            Next pi
            PossibleFormulas(i) = PossibleFormulas(i) & ")"
            i = i + 1
        Next c


        Dim myPosition As Variant
        For Each c In ActiveSheet.Range("G1:G500") ' adapt it
            If c.HasFormula Then
                myPosition = Application.Match(c.Formula, PossibleFormulas(), 0)
                If IsNumeric(myPosition) Then
                    pt.DataBodyRange.Cells(myPosition).Interior.Color = vbYellow
                End If
            End If
        Next c
    End Sub

Be aware: It works only, if =GETPIVOTDATA(...) is the only formula part in your cells. If you need further calculations, like a multiplication (you did it with =GETPIVOTDAT(...)*2), please try to separate that multiplication to an additional column.