PivotCaches are available through workbooks. You can list all of your current caches using the following subkey:
Option Explicit Private Sub listCaches() Dim selectedCache As PivotCache For Each selectedCache In ThisWorkbook.PivotCaches Debug.Print selectedCache.Index Debug.Print selectedCache.Connection Next selectedCache End Sub
You can access the connection you want to change with:
ThisWorkbook.PivotCaches(yourIndex).Connection
Note. After changing the connection, you should call:
ThisWorkbook.PivotCaches(yourIndex).Refresh
Edit: Instead of changing SourceData, you can change CommandText. This should have the same effect. The following code worked for me:
ThisWorkbook.PivotCaches(1).CommandText = "SELECT movies.title, movies.rating, movies.comments FROM `C:\Folder\moviesDB`.movies movies" ThisWorkbook.PivotCaches(1).Refresh
This code also updated my SourceData.
Edit2: Change CommandText command throgh PivotTable:
Sheets("mySheet").PivotTables("PivotTable1").PivotCache.CommandText = "SELECT movies.title as meh, movies.rating, movies.comments FROM `C:\Folder\moviesDB`.movies movies" Sheets("mySheet").PivotTables("PivotTable1").PivotCache.Refresh
Note: moviesDB is a .mdb file, and movies is a table / query
Debug.Print : This can also help you Debug.Print working CommandText before modifying it. This should give you a template for your new CommandText.
source share