How can I get the ListObject object of a PivotTable?

后端 未结 1 1320
不思量自难忘°
不思量自难忘° 2021-01-29 07:06

This question was originally posted as part of an answer by Hugh Seagraves on a related question. He \"wanted to refer to a list object (a table) on one worksheet that a pivot t

相关标签:
1条回答
  • 2021-01-29 07:29

    A PivotTable gets it's data from it's PivotCache. So you just need to use the PivotCache.SourceData property to query the ListObject name.

    For instance, if I make up a PivotTable based on a ListObject, then if I select a cell in the PivotTable then I can use this:

    ? activecell.PivotTable.PivotCache.SourceData
    Table1
    

    Given that Table Names are unique in a workbook and are also Named Ranges, then to set a reference to the actual ListObject you just use something like this:

    Set lo = Range(ActiveSheet.PivotTables("SomePivotTable").PivotCache.S‌​ourceData).ListObjec‌​t
    

    Knowing this, we can write a function that accepts a PivotTable object and returns the ListObject that comprises the PivotTable's data source like so:

    Public Function GetListObjectForPT(pt As PivotTable) As ListObject
    On Error Resume Next ' In case the Pivot isn't created from a ListObject
    Set GetListObjectForPT = Range(pt.PivotCache.SourceData).ListObject
    End Function
    

    ...and you can use it like this:

    Sub Macro1()
    Dim pt As PivotTable
    Dim lo As ListObject
    
    Set pt = Worksheets("SomeWorksheetName").PivotTables("SomePivotTableName")
    Set lo = GetListObjectForPT(pt)
    
    End Sub
    
    0 讨论(0)
提交回复
热议问题