• Hi All

    Please note that at the Chandoo.org Forums there is Zero Tolerance to Spam

    Post Spam and you Will Be Deleted as a User

    Hui...

  • When starting a new post, to receive a quicker and more targeted answer, Please include a sample file in the initial post.

How to derive source sheet name of Pivot Table

ThrottleWorks

Excel Ninja
Hi,

Is it possible to derive sheet name of the pivot table it is linked to.

For example, I have pivot table in Sheet2, pivot range data is in Shee1 of the same file.
If I have to check which sheet is linked to this pivot I will do manually ‘Options -> Change Data Source -> Change Data Source’.

I will copy path populated in browsing window and paste in an excel cell to get the sheet name.

In above mentioned example Pivot path is ‘Sheet1!$A$1:$B$6’. How do I achieve this in VBA. Can anyone please help me in this.


Hope, sample file is not required for this issue. Please let me know if you want sample file. I will try to upload.
 
Check it

http://dailydoseofexcel.com/archives/2010/11/04/getting-the-source-range-of-a-pivot-table-with-vba/


Code:
Option Explicit

Public Function GetRangeFromSourceData(pt As PivotTable) As String
   
    Dim lBang As Long
    Dim lClose As Long
    Dim sAddress As String
    Dim sSheet As String
    Dim sSource As String
    Dim rReturn As Range
   
    Const sBANG As String = "!"
    Const sCLOSE As String = "]"
   
    sSource = Application.ConvertFormula(pt.SourceData, xlR1C1, xlA1)
   
    lBang = InStr(1, sSource, sBANG)
    lClose = InStr(1, sSource, sCLOSE)
   
    If lBang > 0 Then
        sAddress = Mid$(sSource, lBang + 1, Len(sSource))
        If lClose > 0 Then
            sSheet = Mid$(sSource, lClose + 1, lBang - lClose - 1)
        Else
            sSheet = Left$(sSource, lBang - 1)
        End If
        Set rReturn = pt.Parent.Parent.Sheets(sSheet).Range(sAddress)
    Else
        Set rReturn = pt.Parent.Range(sSource)
    End If
   
    GetRangeFromSourceData = rReturn.Address(, , , True)
   
End Function

Sub test()
    Debug.Print GetRangeFromSourceData(Sheet2.PivotTables("PivotTable1"))
End Sub
 
Back
Top