Empty Pivot Cache when creating a pivot table in VBA - excel

I'm using code from https://excelchamps.com/blog/vba-to-create-pivot-table/ to create a pivot table in a long macro I'm writing. The pivot table recently stopped working; this sub runs with no errors but there is no sign of the pivot table. Was fully functional until recently. On trying to troubleshoot I've found the PCache variable is empty, I'm assuming this is where everything is breaking down. The only thing changed since this was working is I changed the cell formats of two columns in the data range for the pivot table, however they seem irrelevant and are not being used for the pivot table.
I have also recorded my own macro to try and fix this. Manually creating the pivot table works fine but this is not a solution to my problem. The recorded macro from this does not work however. I have tried code from multiple different sites as well and have used non-variable ranges but nothing has worked.
Sub bpPivotTBL()
'https://excelchamps.com/blog/vba-to-create-pivot-table/
Dim PSheet As Worksheet
Dim DSheet As Worksheet
Dim PCache As PivotCache
Dim PTable As PivotTable
Dim PRange As Range
Dim LastRow As Long
Dim LastCol As Long
'??Declare Variables
On Error Resume Next
Application.DisplayAlerts = False
Worksheets("PIPE PIVOT").Delete
Sheets.Add Before:=Worksheets("INCOMING")
ActiveSheet.Name = "PIPE PIVOT"
Application.DisplayAlerts = True
Set PSheet = Worksheets("PIPE PIVOT")
Set DSheet = Worksheets("INCOMING")
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)
'=================================================================
'Define Pivot Cache
Set PCache = ActiveWorkbook.PivotCaches.Create _
(SourceType:=xlDatabase, SourceData:=PRange). _
CreatePivotTable(TableDestination:=PSheet.Cells(2, 2), _
TableName:="PipePivot")
'==================================================================
'?Insert Blank Pivot Table
Set PTable = PCache.CreatePivotTable _
(TableDestination:=PSheet.Cells(1, 1), TableName:="PipePivot")
'Insert Row Fields
With ActiveSheet.PivotTables("PipePivot").PivotFields("CNCT")
.Orientation = xlRowField
.Position = 1
End With

The reason you're not getting an error is that you've included an On Error statement, which masks any errors. If you comment out or delete that line, you'll get an error here...
'Define Pivot Cache
Set PCache = ActiveWorkbook.PivotCaches.Create _
(SourceType:=xlDatabase, SourceData:=PRange). _
CreatePivotTable(TableDestination:=PSheet.Cells(2, 2), _
TableName:="PipePivot")
That instruction first creates a pivot cache, then it creates a pivot table, and then it tries to assign the pivot table to PCache, which has been declared as a PivotCache. As a result, you'll get an error. So create only the pivot cache, and then assign it to PCache...
'Define Pivot Cache
Set PCache = ActiveWorkbook.PivotCaches.Create _
(SourceType:=xlDatabase, SourceData:=PRange)

Try the code below, explanations inside the code's comments:
' =================================================================
' Set the Pivot Cache Range
Dim SrcData As String
SrcData = PRange.Address(False, False, xlA1, xlExternal)
' Define and Set the Pivot Cache
Set PCache = ThisWorkbook.PivotCaches.Create(SourceType:=xlDatabase, SourceData:=SrcData)
'==================================================================
' create a new Pivot Table in "PIPE PIVOT" sheet
Set PTable = PSheet.PivotTables.Add(PivotCache:=PCache, TableDestination:=PSheet.Range("A1"), TableName:="PipePivot")
'Insert Row Fields
With PTable.PivotFields("CNCT") ' <<-- Once you set the Pivot-Table, you can use this object in your With Statements
.Orientation = xlRowField
.Position = 1
End With

Related

Currently writing code to create a pivot table that will show the count of IDS that are within a city under a county. My macro only creates a sheet

I got the code from elsewhere and tried to adapt it to my worksheet but it only creates a blank sheet and not the table. I am thinking that there is some error when it tries to get grab the data from the source sheet.
Is there a different way to to fix it or maybe create this table if we can't fix it? Like for example the data is dynamic meaning that each report has a different amount of rows and perhaps later on columns.
for ex:
ID
Name
city
County
23423
Jdoe
d city
d County
That said there are about 30 other columns that are in the report and in the future there may or may not be more columns. The amount of rows number in the 10s of thousands and can be different week to week. I am trying to create a pivot table put an ID to the city they are in and the county it is listed under. I have already created or adapted a different macro to format the document in how we can use it but the pivot table is the last step. Please help!!!
'Declare Variables
Dim PSheet As Worksheet
Dim DSheet As Worksheet
Dim PCache As PivotCache
Dim PTable As PivotTable
Dim PRange As Range
Dim LastRow As Long
Dim LastCol As Long
' Blank Worksheet
On Error Resume Next
Application.DisplayAlerts = False
Worksheets("PivotTable").Delete
Sheets.Add Before:=ActiveSheet
ActiveSheet.Name = "PivotTable"
Application.DisplayAlerts = True
'define worksheet
Set PSheet = Worksheets("PivotTable")
Set DSheet = Worksheets("Data")
' Define Data Range
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)
' Define Pivot Cache
Set PCache = ActiveWorkbook.PivotCaches.Create _
(SourceType:=xlDatabase, SourceData:=PRange). _
CreatePivotTable(TableDestination:=PSheet.Cells(2, 2), _
TableName:="CountyTable")
' Insert Blank Pivot Table
Set PTable = PCache.CreatePivotTable _
(TableDestination:=PSheet.Cells(1, 1), TableName:="CountyTable")
'Insert Row "County" Field
With ActiveSheet.PivotTables("CountyTable").PivotFields("PATIENT_COUNTY")
.Orientation = xlRowField
.Position = 1
End With
'Insert Row "City" Field
With ActiveSheet.PivotTables("CountyTable").PivotFields("PATIENT_CITY")
.Orientation = xlRowField
.Position = 2
End With
'Insert Values "Count of PID" Field
With ActiveSheet.PivotTables("CountyTable").PivotFields( _
"Sum of PATIENT_LOCAL_ID")
.Caption = "Count of PATIENT_LOCAL_ID"
.Function = xlCount
End With
'Format Pivot Table
ActiveSheet.PivotTables("CountyTable").ShowTableStyleRowStripes = True
ActiveSheet.PivotTables("CountyTable").TableStyle2 = "PivotStyleMedium9"
End Sub

Create Calculated field in Pivot Table using VBA

I need the expert help. I want to implement one formula for particular column on Pivot Table created by VB code.
I have written the code that will create the Pivot table with Count the Repeat Data and would like to next column will populate with predefined formula while generating the pivot table by button click event.
Formula will be implemented on column ā€œCā€ as below by using PIVOT Table generation code using VBA module
=IF(AND(B2>=0,B2<=2),1,IF(AND(B2>=3,B2<=5),2,IF(AND(B2>=6,B2<=10),3,IF(AND(B2>=11,B2<=15),4,IF(B2>=16,5)))))
Source worksheet (Rawdata):
Current code and Pivot table :
My current VBA source code for generation of Pivot Table:
Sub PivotTableModule()
'Insert Pivot Table
'Declare Variables
Dim PSheet As Worksheet
Dim DSheet As Worksheet
Dim PCache As PivotCache
Dim PTable As PivotTable
Dim PRange As Range
Dim LastRow As Long
Dim LastCol As Long
'Insert a New Blank Worksheet
On Error Resume Next
Application.DisplayAlerts = False
Worksheets("Pivot").Delete
Sheets.Add Before:=ActiveSheet
ActiveSheet.Name = "Pivot"
Application.DisplayAlerts = True
Set PSheet = Worksheets("Pivot")
Set DSheet = Worksheets("Rawdata")
DSheet.AutoFilterMode = False
'Define Data Range
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)
'Define Pivot Cache
Set PCache = ActiveWorkbook.PivotCaches.Create _
(SourceType:=xlDatabase, SourceData:=PRange)
'CreatePivotTable(TableDestination:=PSheet.Cells(1, 1), _
TableName:="SalesPivotTable")
'Insert Blank Pivot Table
Set PTable = PCache.CreatePivotTable _
(TableDestination:=PSheet.Cells(1, 1), TableName:="PivotTable")
'Insert Row Fields
With PTable.PivotFields("FailureMode")
.Orientation = xlRowField
.Position = 1
End With
'Insert Data Field
With PTable.PivotFields("FailureMode")
.Orientation = xlDataField
.Position = 1
.Description = "Sum of FailureMode"
.Function = xlCount ' xlSum
.NumberFormat = "#,##0"
.Name = "RepeatCount"
End With
End Sub
Current Output (Pivot Generated by Code)
My Expected Pivot Table would be as below :
Formula on Column 'C' while creating the Pivot table
=IF(AND(B2>=0,B2<=2),1,IF(AND(B2>=3,B2<=5),2,IF(AND(B2>=6,B2<=10),3,IF(AND(B2>=11,B2<=15),4,IF(B2>=16,5)))))
HI, I have tried with the Pivot Table Calculated Fields but I am getting the error. I don't know the code is correct or not.
Sub PivotCalculatedFormula()
Dim PvtTbl As PivotTable
Set PvtTbl = Worksheets("Pivot").PivotTables("PivotTable")
'for empty cells in the data area of a PivotTable report, show a specified value, using the PivotTable.NullString Property:
PvtTbl.NullString = "0"
PvtTbl.DisplayNullString = True
PvtTbl.CalculatedFields.Add Name:="RPN", Formula:="=IF(AND(RepeatCount>=0,RepeatCount<=2),1,IF(AND(RepeatCount>=3,RepeatCount<=5),2,IF(AND(RepeatCount>=6,RepeatCount<=10),3,IF(AND(RepeatCount>=11,RepeatCount<=15),4,IF(RepeatCount>=16,5)))))"
With PvtTbl.PivotFields("RPN")
.Orientation = xlDataField
.Function = xlSum
.Position = 3
.NumberFormat = "0.00%"
.Caption = "RPN-%"
End With
End Sub

VBA issue with creating pivot cache

I am struggling to find a solution to the issue I am having; I've been looking all over. I'm not sure if it is how I am obtaining my first row or if it is something else. I have the exact same code (below) setup for another macro but that macro pulls R1C1:lastrow/lastcol. The only difference is: this macro attempts to use a dynamic first row (instead of Set PRange = glData.Cells(1, 1).Resize(LastRow, LastCol)) . I've even tried setting the first row as R10C1(the header row of the source data) and I still get an "Application-defined or object-defined error".
Macro use: Creates pivot table based on source data in range A(y):N(x); x = dynamic lastrow/col, y = dynamic first row. Destination is 4 columns to the right of another pivot table(created by a different sub). They will not overlap (unless something is hidden). I have made this setup manually and it works fine.
Any help is appreciated.
Sub CreateFAPiv()
'
Dim PSheet As Worksheet
Dim wsData As Worksheet: Set wsData = Sheets("Data")
Dim PCache As PivotCache
Dim PTable As PivotTable
Dim PRange As Range
Dim LastRow As Long
Dim LastCol As Long
Dim asset As String
Dim glData As Worksheet: Set glData = Sheets("GL")
asset = glData.Range("B2").Value
Set PSheet = Worksheets("Piv")
'Define Data Range
FirstRow = IIf(IsEmpty(glData.Range("C1")), glData.Range("C1").End(xlDown).Row, 1)
LastRow = glData.Cells(Rows.Count, 1).End(xlUp).Row
LastCol = glData.Cells(1, Columns.Count).End(xlToLeft).Column
Set PRange = glData.Cells(FirstRow, 1).Resize(LastRow, LastCol)
'Define Pivot Cache - This is where I am getting the error
Set PCache = ActiveWorkbook.PivotCaches.Create _
(SourceType:=xlDatabase, SourceData:=PRange). _
CreatePivotTable(TableDestination:=PSheet.Cells(3, 4), _
TableName:="DataPivotTable")
'Insert Blank Pivot Table
Set PTable = PCache.CreatePivotTable _
(TableDestination:=PSheet.Cells(3, 4), TableName:="DataPivotTable")
.....Rest of code....
End Sub

VBA Find Amount Differences Between Books and Sub-Books

I have two large data sets of 70,000+ records which may be more or less depending on the day. Sheet 1 has the information pulled from today and Sheet 2 has the information from yesterday. These are accounting series.
Column E has the region. Column G has several (many) different Book Id's. Those books may have a sub-book in column K. Now column N, has an amount established for each book and sub-book. What I need to do is build a Macro to generate a report that finds the difference between day 1 and day 2 for each book and its sub-book.
Now the tricky part here is that the sub-book in Column K may be used several times in different books from Column G.
What I did was Concatenate all the information in one sheet, build a pivot table and get those differences. But when I try to build the report using a Vlookup and creating a unique identifier I find a dead end since many sub-books are used in different books and regions.
I'm attaching a brief example to show how the data interrelates.
Sheet 1
Sheer2
As you can see Row 2 is in City QN. The Book ID is FLC and Sub-Book TTL555 with 53,000.00. I need to compare this position with the one in sheet 2 (if any) and get the amount difference. Now the thing is that sub-book TTL555 is also used in Row 11 in a different city and under a different book too.
Any ideas?
This is the Code I'm using for the pivot (I don't really need a pivot is just I couldn't figure out another way to do it)
'Create Pivot Table
'Declare Variables
Dim PSheet As Worksheet
Dim DSheet As Worksheet
Dim PCache As PivotCache
Dim PTable As PivotTable
Dim PRange As Range
Dim Lastrow As Long
Dim LastCol As Long
'Insert a New Blank Worksheet
On Error Resume Next
Application.DisplayAlerts = False
Sheets.Add Before:=ActiveSheet
ActiveSheet.Name = "Differences"
Application.DisplayAlerts = True
Set PSheet = Worksheets("Differences")
Set DSheet = Worksheets("Concatenated")
'Define Data Range
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)
'Define Pivot Cache
Set PCache = ActiveWorkbook.PivotCaches.Create _
(SourceType:=xlDatabase, SourceData:=PRange). _
CreatePivotTable(TableDestination:=PSheet.Cells(2, 2), _
TableName:="Differences")
'Insert Blank Pivot Table
Set PTable = PCache.CreatePivotTable _
(TableDestination:=PSheet.Cells(1, 1), TableName:="StatusReport")
'Insert Data Field
ActiveSheet.PivotTables("SD Differences").AddDataField ActiveSheet.PivotTables( _
"Differences").PivotFields("Qty"), "Sum of Qty", xlSum
'Insert Row Fields
With ActiveSheet.PivotTables("Differences").PivotFields("Book ID")
.Orientation = xlRowField
.Position = 1
End With
With ActiveSheet.PivotTables("Differences").PivotFields("Security Code")
.Orientation = xlRowField
.Position = 2
End With
'Insert Column Field
With ActiveSheet.PivotTables("Differences").PivotFields("Position Date")
.Orientation = xlColumnField
.Position = 1
End With
'Add a calculated field to compute variance
With ActiveSheet.PivotTables("Differences").PivotFields("Sum of Qty")
.Calculation = xlDifferenceFrom
.BaseField = "Position Date"
.BaseItem = "(Previous)"
.NumberFormat = "0.00"
.Name = "Position Difference"
End With
'Remove Grand Total
ActiveSheet.PivotTables("Differences").PivotSelect "'Row Grand Total'", _
xlDataAndLabel, True
ActiveSheet.PivotTables("Differences").RowGrand = False
Dim src As Range
Dim ws2 As Worksheet
Set src = Range("B2").CurrentRegion
Set ws2 = ActiveSheet
ws2.ListObjects.Add(SourceType:=xlSrcRange, Source:=src, xlListObjectHasHeaders:=xlYes, tablestyleName:="TableStyleMedium1").Name = "Differences"
Thanks for your help

Create a pivot table in a predefined location

I'm trying to create a pivot table and place it in a predefined location (not a new sheet).
Before running the macro each time, the pivot table is deleted and also the predefined sheet.
I noticed that when you create a table manually, the table name increases by one each time (PivotTable2, PivotTable3...), which I think is where my code is falling down.
I get a Run-time error 5, invalid procedure call or argument on this line:
ActiveWorkbook.PivotCaches.Create
I did check out this thread, which says that you can remove the table name parameter completely, or rename it - however I still get errors.
My code:
Sub CreatePivot()'
' CreatePivot Macro
'
' Set data as table
Sheets("Filtered Flags").Select
Range("A1").Select
Range(Selection, Selection.End(xlToRight)).Select
Range(Selection, Selection.End(xlDown)).Select
ActiveSheet.ListObjects.Add(xlSrcRange, Range("$A$1:$G$16000"), , xlYes).Name _
= "Table1"
' Create worksheet for pivot output
Sheets.Add Before:=ActiveSheet
ActiveSheet.Name = "Flag Pivot"
'Create Pivot Table
Sheets("Filtered Flags").Select
Range("Table1[[#Headers],[Order '#]]").Select
ActiveWorkbook.PivotCaches.Create(SourceType:=xlDatabase, SourceData:= _
"Table1", Version:=6).CreatePivotTable TableDestination:="Flag Pivot!R3C1" _
, TableName:="PivotTable5", DefaultVersion:=6
Sheets("Flag Pivot").Select
Cells(3, 1).Select
With ActiveSheet.PivotTables("PivotTable5").PivotFields("Material #")
.Orientation = xlRowField
.Position = 1
End With
End Sub
So there's a few things to work with here. One of the basics to get started with (and to understand why some of my example below is constructed) is to learn about avoiding the use of Select and Activate. Also, always using Option Explicit will help you sidestep many problems in naming and using variables.
Option Explicit
Public Sub CreatePivot()
'--- establish some basic objects to use...
Dim flagsWS As Worksheet
Set flagsWS = ThisWorkbook.Sheets("Filtered Flags")
'--- now, define the range of cells that contain the data
' and create the pivot cache
With flagsWS
Dim lastRow As Long
Dim lastCol As Long
Dim dataArea As Range
Dim dataAreaString As String
lastRow = .Cells(.Cells.rows.count, 1).End(xlUp).Row
lastCol = .Cells(1, .Cells.Columns.count).End(xlToLeft).Column
Set dataArea = .Range(.Cells(1, 1), .Cells(lastRow, lastCol))
dataAreaString = .Name & "!" & dataArea.Address
Dim pCache As PivotCache
Set pCache = ThisWorkbook.PivotCaches.Create(SourceType:=xlDatabase, _
SourceData:=dataAreaString)
End With
'--- create or clear the sheet for our new pivot
Dim pivotWS As Worksheet
On Error Resume Next
Set pivotWS = ThisWorkbook.Sheets("Flag Pivot")
On Error GoTo 0
If Not pivotWS Is Nothing Then
'--- delete everything on the worksheet so we're starting clean
pivotWS.Cells.Clear
Else
Set pivotWS = ThisWorkbook.Sheets.Add
pivotWS.Name = "Flag Pivot"
End If
'--- finally create the pivot table
Dim flagPT As PivotTable
Set flagPT = pivotWS.PivotTables.Add(PivotCache:=pCache, _
TableDestination:=pivotWS.Range("A4"), _
TableName:="AnnasPivotTable")
End Sub

Resources