我在公式中使用数据透视表中的数据。数据透视表中有很多数据,我需要检查公式中已经使用了哪些数据。
我已经使用了这段代码来标记已使用的数据透视表数据,但是没有用。
Cells(24, "g").Precedents.Interior.ColorIndex = 5
答案 0 :(得分:1)
您已经发现,具有Range.Precedents
公式的单元格的GETPIVOTDATA
仅指向数据透视表的第一个单元格。因此,您不能使用先例来识别数据透视表中已引用的单元格。
我的代码执行以下操作:
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.