Вы можете циклически перемещаться по строкам вашей сводной таблицы, которые PivotTable.PivotRowAxis.PivotLines
.
Их первые левые PivotLineCells
содержат RowField.PivotItems
, которые можно сравнивать и подсчитывать.
Private Sub GetIt()
MsgBox GetPivotItem(ActiveSheet.PivotTables(1), 2, 2)
End Sub
Private Function GetPivotItem(ByRef pt As PivotTable, _
ByRef index1 As Long, ByRef index2 As Long) As String
Dim pl As PivotLine
Dim counter1 As Long, counter2 As Long
Dim remember1 As String, remember2 As String
For Each pl In pt.PivotRowAxis.PivotLines
If pl.LineType = xlPivotLineRegular Then
If pl.PivotLineCells(1).PivotItem.Caption <> remember1 Then
remember1 = pl.PivotLineCells(1).PivotItem.Caption
remember2 = pl.PivotLineCells(2).PivotItem.Caption
counter1 = counter1 + 1
counter2 = 1
ElseIf pl.PivotLineCells(2).PivotItem.Caption <> remember2 Then
remember2 = pl.PivotLineCells(2).PivotItem.Caption
counter2 = counter2 + 1
End If
If counter1 = index1 And counter2 = index2 Then
GetPivotItem = pl.PivotLineCells(2).PivotItem.Caption
Exit For
End If
End If
Next pl
End Function
Выше работает для сводного макета с полями строк в отдельных столбцах (как на скриншоте PivotLine.PivotLineCells.Count > 1
).
Если вы переключаетесь на макет с полями строк с отступом в том же столбце , используйте это вместо:
Private Function GetPivotItemNew(ByRef pt As PivotTable, _
ByRef index1 As Long, ByRef index2 As Long) As String
Dim pl As PivotLine
Dim counter1 As Long, counter2 As Long
For Each pl In pt.PivotRowAxis.PivotLines
If pl.LineType = xlPivotLineRegular Then
If pl.PivotLineCells(1).PivotField = pt.RowFields(1) Then
counter1 = counter1 + 1
counter2 = 0
End If
If pl.PivotLineCells(1).PivotField = pt.RowFields(2) Then counter2 = counter2 + 1
If counter1 = index1 And counter2 = index2 Then
GetPivotItemNew = pl.PivotLineCells(1).PivotItem.Caption
Exit For
End If
End If
Next pl
End Function