Получить заданный элемент поворота в поле второй строки, заданный конкретным элементом поворота в поле первой строки - PullRequest
2 голосов
/ 21 мая 2019

У меня есть сводная таблица с двумя встроенными метками строк и одной переменной данных (см. Ниже). Я хотел бы получить доступ к элементу сводки Rowlabel2 данного индекса, учитывая конкретный элемент сводки Rowlabel1.

Этот вопрос ( Вывести список элементов сводки Excel для поля второй строки (несколько полей строки) с учетом определенного элемента сводки в поле первой строки ) очень близок к моей проблеме, но не совсем то, что мне нужно. Я надеюсь, что есть способ получить предмет, не прибегая к отдельной подпрограмме.

Rowlabel1 Rowlabel2 Value
a          A          1
           B          0
           C          3
b          D          2
           E          8
c          F          5

Например, я хотел бы получить 2-й предмет Rowlabel2 из 2-го предмета Rowlabel1 ("E"). Недвижимость RowFields ( "Rowlabel2"). PivotItems (2) .Caption

возвращает «B», а не «E»

Ответы [ 2 ]

0 голосов
/ 25 мая 2019

Вы можете циклически перемещаться по строкам вашей сводной таблицы, которые 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
0 голосов
/ 23 мая 2019

Public Function getPiv(pt As PivotTable, iRowlabel1 As Integer, iRowlabel2 As Integer) As Variant

'returns item # iRowlabel2 of second Row field of item # iRowlabel1 of first Row field


Dim r As Range
Dim dr As PivotItem

'this captures your first entry in rowlabel1 - change as necessary
Set dr = pt.PivotFields("Rowlabel1").PivotItems(iRowlabel1)

'the macro won't work if the item is collapsed, so we set showDetail to true to expand it
If dr.ShowDetail = False Then
    dr.ShowDetail = True
End If

With dr
    'address what seems to be a bug(??) where if there are more than one data value columns,
    'the datarange appears to shift one row down
    If .DataRange.Columns.Count > 1 Then
        'here we shift back from the datarange to the 2nd column of the pivottable
        Set r = .DataRange.Offset(-1, -(.DataRange.Cells(1, 1).Column - 2))
    Else
        'here we shift back from the datarange to the 2nd column of the pivottable
        Set r = .DataRange.Offset(0, -(.DataRange.Cells(1, 1).Column - 2))
    End If
End With


getPiv = r.Cells(iRowlabel2, 1)


End Function
...