Excel VBA - Refreshing Pivot Cache












1















Recently, I have been looking for ways to share the same pivot cache among a few pivot table as they all use the same data source. This helps to reduce the excel file size substantially as it would be inefficient to create a new pivot cache of the same data for each and every pivot table.



One solution provided to me was to use a static variable which allows to make a single pivot cache which can be shared by the different sub routines. Here is how it is done.



'creates and returns a shared pivotcache object
Function GetPivotCache(pRange As Range) As PivotCache
Static pc As PivotCache 'static variables retain their value between calls

If pc Is Nothing Then 'create if not yet created
Set pc = ActiveWorkbook.PivotCaches.Create _
(SourceType:=xlDatabase, SourceData:=pRange)
End If
Set GetPivotCache = pc
End Function


This is the function used to create the share pivot cache among the subroutines. When creating a pivot table, I call this function to check if a pivot cache has already been created. If it has, it will not create a new copy of the pivot cache and would return the one that is already stored in the static variable.



In case any one is wondering how I use it when creating my pivot table, I will provide some more code to better understand how it is utilized.



Sub pivottable1()

Dim PSheet As Worksheet, DSheet As Worksheet
Dim PCache As PivotCache
Dim PTable As PivotTable
Dim PField As PivotField
Dim pRange As Range
Dim LastRow As Long
Dim LastCol As Long
Dim PvtTable As PivotTable
Dim SheetName As String
Dim PTName As String

SheetName = "MySheetName1"
PTName = "PivotTable1"
On Error Resume Next
Application.DisplayAlerts = False
Worksheets(SheetName).Delete
Sheets.Add After:=ActiveSheet
ActiveSheet.Name = SheetName
Application.DisplayAlerts = True

Set PSheet = Worksheets(SheetName)
Set DSheet = Worksheets(1)

LastRow = DSheet.Cells(Rows.Count, 1).End(xlUp).Row
LastCol = DSheet.Cells(1, Columns.Count).End(xlToLeft).Column
Set pRange = DSheet.Cells(1, 1).Resize(LastRow, LastCol)

Set PCache = GetPivotCache(pRange) 'Here is where I call the function

Set PTable = PCache.CreatePivotTable _
(TableDestination:=PSheet.Cells(1, 1), TABLENAME:=PTName)

Sheets(SheetName).Select
Set PvtTable = ActiveSheet.PivotTables(PTName)
'Rows
With PvtTable.PivotFields("TypeCol")
.Orientation = xlRowField
.Position = 1
End With

With PvtTable.PivotFields("NameCol")
.Orientation = xlRowField
.Position = 2
End With

'Columns
With PvtTable.PivotFields("CategoryCol")
.Orientation = xlColumnField
.Position = 1
End With

'Values
PvtTable.AddDataField PvtTable.PivotFields("Values1"), "Value Balance", xlSum
PvtTable.AddDataField PvtTable.PivotFields("Values2"), "Value 2 Count", xlCount

End Sub


The problems with the current piece of code are:




  1. Only works on one data source. Scenario: If I have 12 pivot tables, 6 pivot tables share data source 1, the other 6 pivot tables share data source 2. This function would only allow for 1 pivot cache unless I make a duplicate of the same function.


  2. Updates on the data source will not be reflected. Scenario: I execute the macro which creates the pivot cache and pivot table. Then I add 10 new records into my data source and use the same macro to refresh the pivot table. These 10 new records will not be included as it still uses the out dated pivot cache.



These problem arises as the pivot cache can only be created once. Once it is created, it sort of "ignores" changes as there is already pivot cache that has been created.



What changes can be done to the GetPivotCache function to help resolve these problem? How does excel know when to create a new pivot cache? I tried recording a macro of creating pivot tables but I do not see anything which looks like a check whether the pivot cache already exists, in order to create a new one.










share|improve this question





























    1















    Recently, I have been looking for ways to share the same pivot cache among a few pivot table as they all use the same data source. This helps to reduce the excel file size substantially as it would be inefficient to create a new pivot cache of the same data for each and every pivot table.



    One solution provided to me was to use a static variable which allows to make a single pivot cache which can be shared by the different sub routines. Here is how it is done.



    'creates and returns a shared pivotcache object
    Function GetPivotCache(pRange As Range) As PivotCache
    Static pc As PivotCache 'static variables retain their value between calls

    If pc Is Nothing Then 'create if not yet created
    Set pc = ActiveWorkbook.PivotCaches.Create _
    (SourceType:=xlDatabase, SourceData:=pRange)
    End If
    Set GetPivotCache = pc
    End Function


    This is the function used to create the share pivot cache among the subroutines. When creating a pivot table, I call this function to check if a pivot cache has already been created. If it has, it will not create a new copy of the pivot cache and would return the one that is already stored in the static variable.



    In case any one is wondering how I use it when creating my pivot table, I will provide some more code to better understand how it is utilized.



    Sub pivottable1()

    Dim PSheet As Worksheet, DSheet As Worksheet
    Dim PCache As PivotCache
    Dim PTable As PivotTable
    Dim PField As PivotField
    Dim pRange As Range
    Dim LastRow As Long
    Dim LastCol As Long
    Dim PvtTable As PivotTable
    Dim SheetName As String
    Dim PTName As String

    SheetName = "MySheetName1"
    PTName = "PivotTable1"
    On Error Resume Next
    Application.DisplayAlerts = False
    Worksheets(SheetName).Delete
    Sheets.Add After:=ActiveSheet
    ActiveSheet.Name = SheetName
    Application.DisplayAlerts = True

    Set PSheet = Worksheets(SheetName)
    Set DSheet = Worksheets(1)

    LastRow = DSheet.Cells(Rows.Count, 1).End(xlUp).Row
    LastCol = DSheet.Cells(1, Columns.Count).End(xlToLeft).Column
    Set pRange = DSheet.Cells(1, 1).Resize(LastRow, LastCol)

    Set PCache = GetPivotCache(pRange) 'Here is where I call the function

    Set PTable = PCache.CreatePivotTable _
    (TableDestination:=PSheet.Cells(1, 1), TABLENAME:=PTName)

    Sheets(SheetName).Select
    Set PvtTable = ActiveSheet.PivotTables(PTName)
    'Rows
    With PvtTable.PivotFields("TypeCol")
    .Orientation = xlRowField
    .Position = 1
    End With

    With PvtTable.PivotFields("NameCol")
    .Orientation = xlRowField
    .Position = 2
    End With

    'Columns
    With PvtTable.PivotFields("CategoryCol")
    .Orientation = xlColumnField
    .Position = 1
    End With

    'Values
    PvtTable.AddDataField PvtTable.PivotFields("Values1"), "Value Balance", xlSum
    PvtTable.AddDataField PvtTable.PivotFields("Values2"), "Value 2 Count", xlCount

    End Sub


    The problems with the current piece of code are:




    1. Only works on one data source. Scenario: If I have 12 pivot tables, 6 pivot tables share data source 1, the other 6 pivot tables share data source 2. This function would only allow for 1 pivot cache unless I make a duplicate of the same function.


    2. Updates on the data source will not be reflected. Scenario: I execute the macro which creates the pivot cache and pivot table. Then I add 10 new records into my data source and use the same macro to refresh the pivot table. These 10 new records will not be included as it still uses the out dated pivot cache.



    These problem arises as the pivot cache can only be created once. Once it is created, it sort of "ignores" changes as there is already pivot cache that has been created.



    What changes can be done to the GetPivotCache function to help resolve these problem? How does excel know when to create a new pivot cache? I tried recording a macro of creating pivot tables but I do not see anything which looks like a check whether the pivot cache already exists, in order to create a new one.










    share|improve this question



























      1












      1








      1








      Recently, I have been looking for ways to share the same pivot cache among a few pivot table as they all use the same data source. This helps to reduce the excel file size substantially as it would be inefficient to create a new pivot cache of the same data for each and every pivot table.



      One solution provided to me was to use a static variable which allows to make a single pivot cache which can be shared by the different sub routines. Here is how it is done.



      'creates and returns a shared pivotcache object
      Function GetPivotCache(pRange As Range) As PivotCache
      Static pc As PivotCache 'static variables retain their value between calls

      If pc Is Nothing Then 'create if not yet created
      Set pc = ActiveWorkbook.PivotCaches.Create _
      (SourceType:=xlDatabase, SourceData:=pRange)
      End If
      Set GetPivotCache = pc
      End Function


      This is the function used to create the share pivot cache among the subroutines. When creating a pivot table, I call this function to check if a pivot cache has already been created. If it has, it will not create a new copy of the pivot cache and would return the one that is already stored in the static variable.



      In case any one is wondering how I use it when creating my pivot table, I will provide some more code to better understand how it is utilized.



      Sub pivottable1()

      Dim PSheet As Worksheet, DSheet As Worksheet
      Dim PCache As PivotCache
      Dim PTable As PivotTable
      Dim PField As PivotField
      Dim pRange As Range
      Dim LastRow As Long
      Dim LastCol As Long
      Dim PvtTable As PivotTable
      Dim SheetName As String
      Dim PTName As String

      SheetName = "MySheetName1"
      PTName = "PivotTable1"
      On Error Resume Next
      Application.DisplayAlerts = False
      Worksheets(SheetName).Delete
      Sheets.Add After:=ActiveSheet
      ActiveSheet.Name = SheetName
      Application.DisplayAlerts = True

      Set PSheet = Worksheets(SheetName)
      Set DSheet = Worksheets(1)

      LastRow = DSheet.Cells(Rows.Count, 1).End(xlUp).Row
      LastCol = DSheet.Cells(1, Columns.Count).End(xlToLeft).Column
      Set pRange = DSheet.Cells(1, 1).Resize(LastRow, LastCol)

      Set PCache = GetPivotCache(pRange) 'Here is where I call the function

      Set PTable = PCache.CreatePivotTable _
      (TableDestination:=PSheet.Cells(1, 1), TABLENAME:=PTName)

      Sheets(SheetName).Select
      Set PvtTable = ActiveSheet.PivotTables(PTName)
      'Rows
      With PvtTable.PivotFields("TypeCol")
      .Orientation = xlRowField
      .Position = 1
      End With

      With PvtTable.PivotFields("NameCol")
      .Orientation = xlRowField
      .Position = 2
      End With

      'Columns
      With PvtTable.PivotFields("CategoryCol")
      .Orientation = xlColumnField
      .Position = 1
      End With

      'Values
      PvtTable.AddDataField PvtTable.PivotFields("Values1"), "Value Balance", xlSum
      PvtTable.AddDataField PvtTable.PivotFields("Values2"), "Value 2 Count", xlCount

      End Sub


      The problems with the current piece of code are:




      1. Only works on one data source. Scenario: If I have 12 pivot tables, 6 pivot tables share data source 1, the other 6 pivot tables share data source 2. This function would only allow for 1 pivot cache unless I make a duplicate of the same function.


      2. Updates on the data source will not be reflected. Scenario: I execute the macro which creates the pivot cache and pivot table. Then I add 10 new records into my data source and use the same macro to refresh the pivot table. These 10 new records will not be included as it still uses the out dated pivot cache.



      These problem arises as the pivot cache can only be created once. Once it is created, it sort of "ignores" changes as there is already pivot cache that has been created.



      What changes can be done to the GetPivotCache function to help resolve these problem? How does excel know when to create a new pivot cache? I tried recording a macro of creating pivot tables but I do not see anything which looks like a check whether the pivot cache already exists, in order to create a new one.










      share|improve this question
















      Recently, I have been looking for ways to share the same pivot cache among a few pivot table as they all use the same data source. This helps to reduce the excel file size substantially as it would be inefficient to create a new pivot cache of the same data for each and every pivot table.



      One solution provided to me was to use a static variable which allows to make a single pivot cache which can be shared by the different sub routines. Here is how it is done.



      'creates and returns a shared pivotcache object
      Function GetPivotCache(pRange As Range) As PivotCache
      Static pc As PivotCache 'static variables retain their value between calls

      If pc Is Nothing Then 'create if not yet created
      Set pc = ActiveWorkbook.PivotCaches.Create _
      (SourceType:=xlDatabase, SourceData:=pRange)
      End If
      Set GetPivotCache = pc
      End Function


      This is the function used to create the share pivot cache among the subroutines. When creating a pivot table, I call this function to check if a pivot cache has already been created. If it has, it will not create a new copy of the pivot cache and would return the one that is already stored in the static variable.



      In case any one is wondering how I use it when creating my pivot table, I will provide some more code to better understand how it is utilized.



      Sub pivottable1()

      Dim PSheet As Worksheet, DSheet As Worksheet
      Dim PCache As PivotCache
      Dim PTable As PivotTable
      Dim PField As PivotField
      Dim pRange As Range
      Dim LastRow As Long
      Dim LastCol As Long
      Dim PvtTable As PivotTable
      Dim SheetName As String
      Dim PTName As String

      SheetName = "MySheetName1"
      PTName = "PivotTable1"
      On Error Resume Next
      Application.DisplayAlerts = False
      Worksheets(SheetName).Delete
      Sheets.Add After:=ActiveSheet
      ActiveSheet.Name = SheetName
      Application.DisplayAlerts = True

      Set PSheet = Worksheets(SheetName)
      Set DSheet = Worksheets(1)

      LastRow = DSheet.Cells(Rows.Count, 1).End(xlUp).Row
      LastCol = DSheet.Cells(1, Columns.Count).End(xlToLeft).Column
      Set pRange = DSheet.Cells(1, 1).Resize(LastRow, LastCol)

      Set PCache = GetPivotCache(pRange) 'Here is where I call the function

      Set PTable = PCache.CreatePivotTable _
      (TableDestination:=PSheet.Cells(1, 1), TABLENAME:=PTName)

      Sheets(SheetName).Select
      Set PvtTable = ActiveSheet.PivotTables(PTName)
      'Rows
      With PvtTable.PivotFields("TypeCol")
      .Orientation = xlRowField
      .Position = 1
      End With

      With PvtTable.PivotFields("NameCol")
      .Orientation = xlRowField
      .Position = 2
      End With

      'Columns
      With PvtTable.PivotFields("CategoryCol")
      .Orientation = xlColumnField
      .Position = 1
      End With

      'Values
      PvtTable.AddDataField PvtTable.PivotFields("Values1"), "Value Balance", xlSum
      PvtTable.AddDataField PvtTable.PivotFields("Values2"), "Value 2 Count", xlCount

      End Sub


      The problems with the current piece of code are:




      1. Only works on one data source. Scenario: If I have 12 pivot tables, 6 pivot tables share data source 1, the other 6 pivot tables share data source 2. This function would only allow for 1 pivot cache unless I make a duplicate of the same function.


      2. Updates on the data source will not be reflected. Scenario: I execute the macro which creates the pivot cache and pivot table. Then I add 10 new records into my data source and use the same macro to refresh the pivot table. These 10 new records will not be included as it still uses the out dated pivot cache.



      These problem arises as the pivot cache can only be created once. Once it is created, it sort of "ignores" changes as there is already pivot cache that has been created.



      What changes can be done to the GetPivotCache function to help resolve these problem? How does excel know when to create a new pivot cache? I tried recording a macro of creating pivot tables but I do not see anything which looks like a check whether the pivot cache already exists, in order to create a new one.







      excel vba excel-vba






      share|improve this question















      share|improve this question













      share|improve this question




      share|improve this question








      edited Nov 23 '18 at 4:06







      DSM

















      asked Nov 22 '18 at 4:44









      DSMDSM

      676




      676
























          0






          active

          oldest

          votes











          Your Answer






          StackExchange.ifUsing("editor", function () {
          StackExchange.using("externalEditor", function () {
          StackExchange.using("snippets", function () {
          StackExchange.snippets.init();
          });
          });
          }, "code-snippets");

          StackExchange.ready(function() {
          var channelOptions = {
          tags: "".split(" "),
          id: "1"
          };
          initTagRenderer("".split(" "), "".split(" "), channelOptions);

          StackExchange.using("externalEditor", function() {
          // Have to fire editor after snippets, if snippets enabled
          if (StackExchange.settings.snippets.snippetsEnabled) {
          StackExchange.using("snippets", function() {
          createEditor();
          });
          }
          else {
          createEditor();
          }
          });

          function createEditor() {
          StackExchange.prepareEditor({
          heartbeatType: 'answer',
          autoActivateHeartbeat: false,
          convertImagesToLinks: true,
          noModals: true,
          showLowRepImageUploadWarning: true,
          reputationToPostImages: 10,
          bindNavPrevention: true,
          postfix: "",
          imageUploader: {
          brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
          contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
          allowUrls: true
          },
          onDemand: true,
          discardSelector: ".discard-answer"
          ,immediatelyShowMarkdownHelp:true
          });


          }
          });














          draft saved

          draft discarded


















          StackExchange.ready(
          function () {
          StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53424024%2fexcel-vba-refreshing-pivot-cache%23new-answer', 'question_page');
          }
          );

          Post as a guest















          Required, but never shown

























          0






          active

          oldest

          votes








          0






          active

          oldest

          votes









          active

          oldest

          votes






          active

          oldest

          votes
















          draft saved

          draft discarded




















































          Thanks for contributing an answer to Stack Overflow!


          • Please be sure to answer the question. Provide details and share your research!

          But avoid



          • Asking for help, clarification, or responding to other answers.

          • Making statements based on opinion; back them up with references or personal experience.


          To learn more, see our tips on writing great answers.




          draft saved


          draft discarded














          StackExchange.ready(
          function () {
          StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53424024%2fexcel-vba-refreshing-pivot-cache%23new-answer', 'question_page');
          }
          );

          Post as a guest















          Required, but never shown





















































          Required, but never shown














          Required, but never shown












          Required, but never shown







          Required, but never shown

































          Required, but never shown














          Required, but never shown












          Required, but never shown







          Required, but never shown







          Popular posts from this blog

          Costa Masnaga

          Fotorealismo

          Sidney Franklin