Pivot Cache Refresh VBA - vba

Hi I have a pivot table set up which I need to refresh on a VBA command. However when I refresh the pivot command it excludes some of the required Column label Values. I believe I have to change the Pivot Cache which was set up originally but not sure how to? (Can anyone advise how to do this?)
The code I am using is below:
Worksheets("Summary by Account").PivotTables("PivotTable1").RefreshTable
Dim pt As PivotTable
Dim pf As PivotField
Dim pi As PivotItem
For Each pt In ActiveSheet.PivotTables
pt.ManualUpdate = True
pt.PivotCache.MissingItemsLimit = xlMissingItemsNone
For Each pf In pt.PivotFields
If pf.Orientation <> 0 Then
If pf.Orientation = xlPageField Then
pf.CurrentPage = "(All)"
Else
For Each pi In pf.PivotItems
pi.Visible = True
Next pi
End If
End If
Next pf
pt.ManualUpdate = False
Next pt
Set pi = Nothing
Set pf = Nothing
Set pt = Nothing
Set wks = Nothing
With ActiveSheet.PivotTables("PivotTable1").PivotFields("Nominal / Category")
.PivotItems("(blank)").Visible = False
End With

I am using the following code to refresh my PIVOT Table Cache, my source file is located in a remote workbook, so you can adjust the parameters to your needs.
Const Pivot_sht_str As String = "Summary by Account"
Const Pivot_name_str As String = "PivotTable1"
Dim pt As PivotTable
Dim Data_FilePath As String
Dim Data_book As String
Dim Data_sht_str As String
Dim Data_sht As Worksheet
Dim Data_range As Range
Dim Data_range_str As String
Dim lrow As Long
' Asign Pivot table to pt
Set pt = Worksheets(Pivot_sht_str).PivotTables(Pivot_name_str)
' Asign Pivot's Data source parameters >> this part is needed only if source for PIVOT table is data in another workbook
Data_FilePath = "\\Folder\Nested Folder\Nested Folder 2\" 'modify to your needs
Data_book = "File_Name.xlsx" 'modify to your needs
Data_sht_str = "Worksheet Name" 'modify to your needs
Application.ScreenUpdating = False
Application.DisplayAlerts = False
On Error Resume Next
Workbooks.Open (Data_FilePath & Data_book)
Set Data_sht = ActiveWorkbook.Worksheets(Data_sht_str)
lrow = Data_sht.Cells.Find("*", SearchOrder:=xlByRows, SearchDirection:=xlPrevious).row
Data_range_str = Data_sht.Name & "!" & Range("$A$1:$P$" & lrow).Address '.Address(ReferenceStyle:=xlR1C1) ' adjust Columns to your needs
Set Data_range = Data_sht.Range(Data_range_str)
' check if Data Range consists of a legal range, Workbook and worksheet are legal
If Not Data_range Is Nothing Then
Data_range_str = Data_FilePath & "[" & Data_book & "]" & Data_sht.Name & "!" & Range("$A$1:$P$" & lrow).Address
'Change Pivot Table Data Source Range Address (refresh it's cache data)
pt.ChangePivotCache ThisWorkbook.PivotCaches.Create(xlDatabase, Data_range_str, xlPivotTableVersion12) ' verify last parameter to have the correct Excel version
pt.RefreshTable
On Error Resume Next
ActiveWorkbook.Close (False) ' Workbooks(Data_FilePath & Data_book).Close savechanges:=False
End If
Application.ScreenUpdating = True
Application.DisplayAlerts = True
If Data_range Is Nothing Then Exit Sub

My method to updating pivot caches with new information is to store all of the data on a separate sheet within the workbook and put in an extending range formula named range - with this formula
=OFFSET($A$1,0,0,COUNTA($A:$A),COUNTA($1:$1))
Then, in VBA, use:
ThisWorkbook.RefreshAll
Hope that helps!

I use this code to reset all pivot table caches in the entire workbook and prevent the pivot table drop-down filters from showing missing items that don't actually exist in the underlying data.
Sub PivotCacheReset()
' When a data set is pivoted and then some of the underlying data is
' removed, even after a refresh old removed values can still remain in the
' pivot filter. This macro changes the properties of all pivot tables in
' the active workbook, to prevent missing items from appearing, or clear
' items that have appeared. It also resets all pivot table caches in the
' active workbook.
Dim wb As Workbook
Set wb = ActiveWorkbook
Dim iWs As Worksheet
Dim pvt As PivotTable
Dim iProtectState As Boolean
' Loop through each worksheet.
For Each iWs In wb.Worksheets
' If the worksheet is protected, unprotect it. Remember
' it was protected so that it can be re-protected later.
iProtectState = False ' Reset variable that remembers if each sheet is protected.
If iWs.ProtectContents = True Then
' Worksheet is protected.
iWs.Unprotect ' Unprotect the worksheet.
iProtectState = True ' Remember that this worksheet was protected.
End If
' Loop through each pivot table in the sheet.
For Each pvt In iWs.PivotTables
pvt.PivotCache.MissingItemsLimit = xlMissingItemsNone ' Don't allow missing items in the pivot table filters.
pvt.PivotCache.Refresh ' Reset the pivot table cache including any missing items.
Next pvt
' If the worksheet was originally protected, re-protect it.
If iProtectState = True Then iWs.Protect
Next iWs
End Sub

Related

VBA: Run-time error '1004': Method 'PivotTables' of object '_Worksheet' failed

I am trying to write a macro that updates my pivot table when new data is put into the original table. I keep on receive an error and do not know how to fix it. Here's what I have so far.
Sub UpdatePivotTableRange()
Dim Data_Sheet As Worksheet
Dim Pivot_Sheet As Worksheet
Dim StartPoint As Range
Dim PivotName As String
Dim NewRange As String
Dim LastCol As Long
Dim lastRow As Long
Set Data_Sheet = ThisWorkbook.Worksheets("Data insert")
Set Pivot_Sheet = ThisWorkbook.Worksheets("CC_Users")
PivotName = PivotTable6 Data_Sheet.Activate
Set StartPoint = Data_Sheet.Range("A1")
LastCol = StartPoint.End(xlToRight).Column
DownCell = StartPoint.End(xlDown).Row
Set DataRange = Data_Sheet.Range(StartPoint, Cells(DownCell, LastCol))
NewRange = Data_Sheet.Name & "!" & DataRange.Address(ReferenceStyle:=xlR1C1)
Pivot_Sheet.PivotTables (PivotName)
ChangePivotCache.ActiveWorkbook PivotCaches.Create SourceType:=xlDatabase, SourceData:=NewRange Pivot_Sheet.PivotTables(PivotName).RefreshTable
Pivot_Sheet.Activate MsgBox "Your Pivot table is now updated" End Sub
Thank you
This needs to be pasted in VBE on the sheet that holds your table that will be changed.
As is, this will refresh every pivot table (along with pivot charts) that exist on your workbook when ANY cell on your sheet with the table is changed.
Private Sub Worksheet_SelectionChange(ByVal Target As Range)
Application.DisplayAlerts = False
Application.EnableEvents = False
ThisWorkbook.RefreshAll
Application.DisplayAlerts = True
Application.EnableEvents = True
Msgbox "All Pivots Refreshed"
End Sub

Run time error 1004 "Cannot open PivotTable source file"

I want to create a pivot table based on a dataset (contained in a worksheet) in the same workbook.
The workbook is open when I run the macro. The dataset comes from running a query in Access, and then export it to excel. I also tried to save the workbook prior to running the macro. I am using excel 2016.
This is my code:
Sub BusinessInteligenceCreatePivotTable()
Dim PivotSheet As Worksheet
Dim pvtCache As PivotCache
Dim pvt As PivotTable
'Determine the data range you want to pivot
Set pvtCache = ThisWorkbook.PivotCaches.Create(SourceType:=xlDatabase, SourceData:=wsPartsMachines.Name & "'!" & wsPartsMachines.Range("A1").CurrentRegion.Address, Version:=xlPivotTableVersion15)
'Create a new worksheet
With ThisWorkbook
Set PivotSheet = .Sheets.Add(After:=.Sheets(.Sheets.Count))
PivotSheet.Name = "Production Schedule"
End With
PivotSheet.Activate
Range("A1").Select
'Create Pivot table from Pivot Cache
'Set pvt = pvtCache.CreatePivotTable(TableDestination:=ActiveCell, TableName:="ProductionSchedule")
Set pvt = PivotSheet.PivotTables.Add(PivotCache:=pvtCache, TableDestination:=ActiveCell, TableName:="ProdSched")
End Sub
The two last lines generates the same error message. "Run time error 1004. Cant open PivotTable source file 'C:\Users...'".
Does anybody know how to solve this problem?
Thanks.
EDIT
When I record a macro, VBA gives me this code (it works).
Sub BusinessInteligenceCreatePivotTable()
Dim PivotSheet As Worksheet
With ThisWorkbook
Set PivotSheet = .Sheets.Add(After:=.Sheets(.Sheets.Count))
PivotSheet.Name = "Production Schedule"
End With
PivotSheet.Activate
Range("A1").Select
ActiveWorkbook.PivotCaches.Create(SourceType:=xlDatabase, SourceData:= _
"Parts & Machines2!R1C1:R1328C14", Version:=6).CreatePivotTable _
TableDestination:=ActiveCell, TableName:="PivotTable1", DefaultVersion:=6
End Sub
I want my SourceData's range to be dynamically set. My efforts to do it generates (with debug.print): 'Parts & Machines2'!R1C1:R1328C14
It seems to be different from the macro-recorded :"Parts & Machines2!R1C1:R1328C14".
Is it this difference that generates the error that i cant find the source data?
Screenshot of Data.
I am not so sure where you define wsPartsMachines as Worksheet and where you set it.
However, the error is in the line:
Set pvtCache = ThisWorkbook.PivotCaches.Create(SourceType:=xlDatabase, SourceData:=wsPartsMachines.Name & "'!" & wsPartsMachines.Range("A1").CurrentRegion.Address, Version:=xlPivotTableVersion15)
If you add a line after:
Debug.Print pvtCache.SourceData
You will get 'Sheet3'''!R1C1:R6C3 in the immediate window - you have one ' too many. (I have used "Sheet3" as my SourceData)
Try to modify this line to :
Set pvtCache = ThisWorkbook.PivotCaches.Create(SourceType:=xlDatabase, SourceData:=wsPartsMachines.Name & "!" & wsPartsMachines.Range("A1").CurrentRegion.Address)
Edit 1: Try a different approach, bring the data source direclty as Range:
Dim pvtDataRng As Range
Set wsPartsMachines = Sheets("Parts & Machines2")
' set the Pivot Table Data Source Range
Set pvtDataRng = wsPartsMachines.Range("A1").CurrentRegion
Set pvtCache = ThisWorkbook.PivotCaches.Create(SourceType:=xlDatabase, SourceData:=pvtDataRng)
'Create Pivot table from Pivot Cache
Set pvt = PivotSheet.PivotTables.Add(PivotCache:=pvtCache, TableDestination:=ActiveCell, TableName:="ProdSched")
This code works. Still not sure why SourceData does not work. With small changes in the code that Shai Rado suggested it worked. Below is the code.
Sub BusinessInteligenceCreatePivotTable()
Dim PivotSheet As Worksheet
Dim pvtCache As PivotCache
Dim pvtTable As PivotTable
Dim ws1PartMachines As Worksheet
Dim pvtDataRng As Range
'Determine the data range you want to pivot
Set ws1PartsMachines = Worksheets("Parts & Machines2")
' set the Pivot Table Data Source Range
Set pvtDataRng = ws1PartsMachines.Range("A1").CurrentRegion
Set pvtCache = ThisWorkbook.PivotCaches.Create(SourceType:=xlDatabase, SourceData:=pvtDataRng)
Debug.Print pvtCache.SourceData
'Create a new worksheet
With ThisWorkbook
Set PivotSheet = .Sheets.Add(After:=.Sheets(.Sheets.Count))
PivotSheet.Name = "Production Schedule2"
End With
PivotSheet.Activate
Range("A1").Select
'Create Pivot table from Pivot Cache
Set pvtTable = PivotSheet.PivotTables.Add(PivotCache:=pvtCache, TableDestination:=ActiveCell, TableName:="ProdSched")
End Sub

Splitting Workbook into separate workbooks including all tabs

I looked at Bhaskar's code on the post located here (VBA code to split an excel file into multiple workbooks based on the contents of a column?)
and have modified it to the point where it recognizes the field I need the workbooks split on but I am getting a variable not defined error at the following section
For Each rw In UsedRange.Rows
I appreciate any help you could provide
I have included the code.
Option Explicit
Dim personRows As Range 'Stores all of the rows found
'Split data into separate columns baed on the names defined in
'a RepList on the 'Names' sheet.
Sub SplitSalesData()
Dim wb As Workbook
Dim p As Range
Dim counter2 As Integer
Dim i As Integer
counter2 = 0
i = 0
Application.ScreenUpdating = False
' in my case i am generating new excel based on every 8 reacords from begining. You can simplyfy this logic based on your need.
For Each p In Sheets("Source").Range("AM1") ' Give the name of your input sheet and column
If i = 0 Then ' We are starting, so generate new excel in memeory.
Workbooks.Add
Set wb = ActiveWorkbook
ThisWorkbook.Activate
End If
WritePersonToWorkbook wb, p.Value
i = i + 1 ' Increment the counter reach time
If i = 8 Then ' As my need is after processing every 8 uniqe record just save the excel sheet and reset the processing
counter2 = counter2 + 1
wb.SaveAs ThisWorkbook.Path & "\salesdata_" & CStr(counter2) ' save the data at current directory location.
wb.Close
Set personRows = Nothing ' Once the process has completed for curent excelsheet, set the personRows as NULL
i = 0
End If
Next p
Application.ScreenUpdating = True
Set wb = Nothing
End Sub
'Writes all the data rows belonging to a RepList
Sub WritePersonToWorkbook(ByVal SalesWB As Workbook, _
ByVal Person As String)
Dim rw As Range
Dim firstRW As Range
For Each rw In UsedRange.Rows - ***ERROR IS HERE***
If Not Not firstRW Is Nothing And Not IsNull(rw) Then
Set firstRW = rw ' WE want to add first row in each excel sheet.
End If
If Person = rw.Cells(1, 5) Then ' My filter is working based on "FeederID"
If personRows Is Nothing Then
Set personRows = firstRW
Set personRows = Union(personRows, rw)
Else
Set personRows = Union(personRows, rw)
End If
End If
Next rw
personRows.Copy SalesWB.Sheets(1).Cells(1, 1) ' Adding data in Excel sheet.
End Sub

Macro that loops through drop down and creates a worksheet for each drop down selection

So I have a dashboard sheet named "Business Plans" where I have a dropdown in cell A2 that's a dropdown selection of a range called "Facilities" and all dashboard data are driven off of lookups. What I want to do is First create a new workbook than a new tab for each dropdown selection with the tab in the same format but the data pasted as values. I attempted the following code that I created to save every dropdown selection as PDF but I have been unsuccessful. Any insight on how I can get this code working will be great.
Sub Worksheet_Generator()
Dim cell As Range
Dim wsSummary As Worksheet
Dim counter As Long
Set wsSummary = Sheets("Business Plans")
For Each cell In Worksheets("dd").Range("$C3:$C75")
If cell.Value = "" Then
counter = counter + 1
Application.StatusBar = "Processing file: " & counter & "/1042"
Else
counter = counter + 1
Application.StatusBar = "Processing file: " & counter & "/1042"
With wsSummary
.Range("$A$2").Value = cell.Value
ActiveSheet.Copy After:=Worksheets(Worksheets.Count)
ActiveSheet.Copy
With ActiveSheet.UsedRange
.Value = .Value
End With
End With
End If
Next cell
Set wsSummary = Nothing
End Sub
I think you are looking for something like the below (adapted from copying-dynamic-rows-into-new-workbook-and-save-it).
Option Explicit
Sub grabber()
Dim thisWb As Workbook: Set thisWb = ThisWorkbook
Dim thisWs As Worksheet: Set thisWs = thisWb.Worksheets("dd") 'replace with relevant name
Dim newBook As Workbook
Dim newws As Worksheet
Dim pathToNewWb As String
Dim uKeys
Dim currentPath, columnWithKey, numCols, numRows, uKey, dataStartRow, columnKeyName
'nobody likes flickering screens
Application.ScreenUpdating = False
'remove any filter applied to the data
thisWs.AutoFilterMode = False
'get the path of the workbook folder
currentPath = Application.ThisWorkbook.Path
'Set the stage
'###Hardcode###
columnKeyName = "Facility" 'name of the column with the facility values
dataStartRow = 4 'this is a pure guess, correct as relevenat. Use the header row index
pathToNewWb = currentPath & "/Business Plans.xlsx" ' where to put the new excel, if you want a saveas prompt you should google "Application.FileDialog(msoFileDialogSaveAs)"
uKeys = Range("Facilities").Value
'###Hardcode End###
columnWithKey = thisWs.Range(dataStartRow & ":" & dataStartRow).Find(what:=columnKeyName, LookIn:=xlValues).Column
numCols = thisWs.UsedRange.Columns.Count
'extract the index of the last used row in the worksheet
numRows = thisWs.UsedRange.Rows.Count
'create the new workbook
Set newBook = Workbooks.Add
'loop the facilities, and do the work
For Each uKey In uKeys
'Filter the keys column for a unique key
thisWs.Range(thisWs.Cells(dataStartRow, 1), thisWs.Cells(numRows, numCols)).AutoFilter field:=columnWithKey, Criteria1:=uKey
'copy the sheet
thisWs.UsedRange.Copy
'Create a new ws for the facility, and paste as values
Set newws = newBook.Worksheets.Add
With newws
.Name = uKey 'I assume the name of the facility is the relevant sheet name
.Range("A1").PasteSpecial xlPasteValues
End With
'remove autofilter (paranoid parrot)
thisWs.AutoFilterMode = False
Next uKey
'save the new workbook
newBook.SaveAs pathToNewWb
newBook.Close
End Sub
EDIT:
As I have not seen your data, I would not be surprised if it requires some revision.
First I try to "frame" the range of the worksheet "dd" that contains the data (the ###Hardcode### bit), define the path for the output, and identify the column that can be filtered for the values corresponding to the named range "Facilities".
I retrieve the values of the named range "Facilities" (into uKeys), and create the output workbook (newBook). Then we go through each value (uKey) from the uKeys in the for loop. Within the loop, I apply an autofilter for the uKey. The filtration is followed by creation of a sheet (newWs) in newBook, and a copy paste of the filtered worksheet "dd" into newWs. we then turn off the autofilter, and the worksheet "dd" is returned to its unfiltered state.
At the end we save newBook to the desired location, and close it.

Report Split - Excel VBA Doesn't Copy all Rows and runs Indefinetly

I have written the following Excel VBA Macro, its job is to split a report based on CountryCode. It creates a new workbook, copies the relevant rows to a new workbook, saves the workbook by the CountryCode.
The problem I encouter is missing rows and for one worksheet, it continues running on empty rows? - Basically it doesn't stop and copies over empty rows.
Has cell formatting anything to do with it?
There is another Macro that runs only once which creates the workbooks first. It is only run once on the first worksheet, never again.
Sub RUN2_ReportSplitterOptimized()
Application.DisplayAlerts = False
Application.EnableEvents = False
' Current Workbook
Dim cW As Workbook
Dim cWL As String
Dim cWN As String
Set cW = ThisWorkbook
cWL = cW.Path
cWN = cW.Name
' Current Worksheet
Dim cS As Worksheet
Set cS = ActiveSheet
Do Until IsEmpty(ActiveCell)
' Current Active Cell
Dim aC As Range
Set aC = ActiveCell
' Split input string
Dim CC As String
CC = splitCC(aC.Text)
Dim wb As Workbook
Dim ws As Worksheet
On Error Resume Next
Set wb = Workbooks(CC & ".xlsx")
If Err.Number <> 0 Then
Set wb = Workbooks.Open(cWL & "\" & CC & ".xlsx")
' Create the worksheet
Set ws = wb.Sheets.Add
' Copy the row to the worksheet
ws.Rows(1).Value = cS.Rows(1).Value
ws.Rows(2).Value = aC.EntireRow.Value
With ws
.Name = cS.Name
End With
Else
wb.Activate
On Error Resume Next
Set ws = wb.Sheets(cS.Name)
If Err.Number <> 0 Then
Set ws = wb.Sheets.Add
' Copy the row to the worksheet
ws.Rows(1).Value = cS.Rows(1).Value
ws.Rows(2).Value = aC.EntireRow.Value
With ws
.Name = cS.Name
End With
Else
LastRow = ws.Cells(ws.Rows.Count, "A").End(xlUp).Row
ws.Rows(LastRow + 1).Value = aC.EntireRow.Value
End If
End If
wb.Save
cW.Activate
aC.Offset(1, 0).Select
Loop
Dim wbk As Workbook
For Each wbk In Workbooks
If Len(wbk.Name) = 7 Then
wbk.Close
End If
Next
End Sub
Function splitCC(countrycode As String) As String
If Len(countrycode) < 3 Then
splitCC = countrycode
Else
splitCC = Mid(countrycode, InStr(countrycode, "(") + 1, 2)
End If
End Function
Solved it.
I have used filters as recommended by #sous2817
Instead of running couple of hours - it does the entire job within 2 minutes :D
Thanks for your help
Problem has been solved here: Excel VBA AutoFilter adds empty rows