Pivot Table VBA Error from Recorded Macro - vba

Below is my update to the code. TableX is the referenced table that my pivot tables will use. After declaring the 'shtReport' variable as a Worksheet and further naming the variable, the error 'Object variable or With block variable not set' occurs.
Option Explicit
Sub SutoPivot()
Dim PvtTbl As PivotTable
Dim PvtCache As PivotCache
Dim shtReport As Worksheet
' set the Pivot Cache (NOT SURE what is "TableX" ?)
Set PvtCache = ActiveWorkbook.PivotCaches.Create(SourceType:=xlDatabase, SourceData:="TableX", Version:=xlPivotTableVersion14)
Set shtReport = Worksheets("Invoice Data")
' add this line in case the Pivot table doesn't exit >> first time running this Macro
On Error Resume Next
Set PvtTbl = Worksheets("Invoice Data").PivotTables("PivotTable1a")
On Error GoTo 0
If PvtTbl Is Nothing Then
' create a new Pivot Table in "Invoice Data" sheet, start from Cell Y1
Set PvtTbl = shtReport.PivotTables.Add(PivotCache:=PvtCache, TableDestination:=Worksheets("Invoice Data").Range("Y1"), _ TableName:="PivotTable1a")
With PvtTbl.PivotFields("Sales Director")
.Orientation = xlRowField
.Position = 1
End With
With PvtTbl.PivotFields("Manager")
.Orientation = xlRowField
.Position = 2
End With
With PvtTbl.PivotFields("Owner")
.Orientation = xlRowField
.Position = 3
End With
With PvtTbl.PivotFields("Account Name")
.Orientation = xlRowField
.Position = 4
End With
With PvtTbl.PivotFields("Business Name")
.Orientation = xlRowField
.Position = 5
End With
With PvtTbl.PivotFields("Annual Aggregate Volume")
.Orientation = xlValuesField
.Position = 1
End With
PvtTbl.AddDataField PvtTbl.PivotFields("Annual Aggregate Volume"),
"Sum of Annual Aggregate Volume", xlSum
With PvtTbl.PivotFields("Sum of Annual Aggregate Volume")
.NumberFormat = "#,##0"
End With
Else
' just refresh the Pivot cache with the updated Range
PvtTbl.ChangePivotCache PvtCache
PvtTbl.RefreshTable
End If
End Sub

The code below will get you started on automating the creation and updating of PivotTables in VBA:
Option Explicit
Sub SutoPivot()
Dim PvtTbl As PivotTable
Dim PvtCache As PivotCache
' set the Pivot Cache (NOT SURE what is "TableX" ?)
Set PvtCache = ActiveWorkbook.PivotCaches.Create(SourceType:=xlDatabase, SourceData:="TableX", Version:=xlPivotTableVersion14)
' add this line in case the Pivot table doesn't exit >> first time running this Macro
On Error Resume Next
Set PvtTbl = Worksheets("Invoice Data").PivotTables("PivotTable1a")
On Error GoTo 0
If PvtTbl Is Nothing Then
' create a new Pivot Table in "Invoice Data" sheet, start from Cell Y1
Set PvtTbl = shtReport.PivotTables.Add(PivotCache:=PvtCache, TableDestination:=Worksheets("Invoice Data").Range("Y1"), TableName:="PivotTable1a")
With PvtTbl.PivotFields("Director")
.Orientation = xlRowField
.Position = 1
End With
With PvtTbl.PivotFields("Manager")
.Orientation = xlRowField
.Position = 2
End With
With PvtTbl.PivotFields("Owner")
.Orientation = xlRowField
.Position = 3
End With
With PvtTbl.PivotFields("Account Name")
.Orientation = xlRowField
.Position = 4
End With
With PvtTbl.PivotFields("Business Name")
.Orientation = xlRowField
.Position = 5
End With
PvtTbl.AddDataField PvtTbl.PivotFields("Annual Aggregate Volume"), _
"Sum of Annual Aggregate Volume", xlSum
With PvtTbl.PivotFields("Sum of Annual Aggregate Volume")
.NumberFormat = "#,##0"
End With
Else
' just refresh the Pivot cache with the updated Range
PvtTbl.ChangePivotCache PvtCache
PvtTbl.RefreshTable
End If
End Sub

Related

My code to Create a Pivot works but the First row field does not work

I have been trying to create a pivot table in VBA and I partially succeeded even after creating the pivot cache and the pivot table the first rowFeild does not come up but the second rowFeild shows up even though I have numbered them as .position=1 and .position=2. Please can anyone help me as I am new to VBA coding and need help to fix this..
Where I have given the xlRowField to be "Natural Account" I have that column in my data and also the column "Natural Account Description" but still the code skips the "Natural Account" completely in row field and moves to the second not sure why. Also how to put it in a classic Pivot view my code is not working for that as well.
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
'On Error Resume Next
Worksheets("TempData").Activate
Application.DisplayAlerts = False
Worksheets("PivotTable").Delete
Sheets.Add before:=ActiveSheet
ActiveSheet.Name = "PivotTable"
Application.DisplayAlerts = True
Set PSheet = Worksheets("PivotTable")
Set DSheet = Worksheets("TempData")
'LastRow = DSheet.Cells(Rows.Count, 1).End(xlUp).Select
'LastCol = DSheet.Cells(1, Columns.Count).End(xlToLeft).Column
Set PRange = DSheet.Range("A1").CurrentRegion
Set PCache = ActiveWorkbook.PivotCaches.Create(SourceType:=xlDatabase, SourceData:=PRange). _
CreatePivotTable(tabledestination:=PSheet.Cells(2, 2), TableName:="SalesPivotTable")
Set PTable = PCache.CreatePivotTable(tabledestination:=PSheet.Cells(2, 2), TableName:="SalesPivotTable")
With ActiveSheet.PivotTables("SalesPivotTable").PivotFields("Natural Account")
.Orientation = xlRowField
.Position = 1
'.InGridDropZones = True
'.RowAxisLayout xlTabularRow
End With
With ActiveSheet.PivotTables("SalesPivotTable").PivotFields("Natural Account Description")
.Orientation = xlRowField
.Position = 2
End With
With ActiveSheet.PivotTables("SalesPivotTable").PivotFields("ME")
.Orientation = xlColumnField
.Position = 1
End With
With ActiveSheet.PivotTables("SalesPivotTable").PivotFields("Net Closing Balance")
.Orientation = xlDataField
.Position = 2
.Function = xlSum
End With
ActiveSheet.PivotTables("SalesPivotTable").RowAxisLayout xlTabularRow
'With ActiveSheet.PivotTables("SalesPivotTable")
'.InGridDropZones = True
'.RowAxisLayout xlTabularRow
'End With

VBA - Add PivotField Filter to Pivot Table

I have code that creates a Pivot Table and adds the desired "PivotFields" to the table.. The one thing I cannot seem to figure out is how to add a "Pivot Field" under the "Filters" area.
Here is the code I have:
Sub CreatePivotTable()
'PURPOSE: Creates a brand new Pivot table on a new worksheet from data in the ActiveSheet
'Source: www.TheSpreadsheetGuru.com
Dim pvtSht As Worksheet
Dim summarySht As Worksheet
Dim pvtCache As PivotCache
Dim pvt As PivotTable
Dim StartPvt As String
Dim SrcData As String
Dim pf As PivotField
'Determine the data range you want to pivot
SrcData = ActiveSheet.UsedRange.Address(ReferenceStyle:=xlR1C1)
'Create a new worksheet
Set pvtSht = Sheets.Add
ActiveSheet.Name = "PivotTable"
'Where do you want Pivot Table to start?
StartPvt = pvtSht.Name & "!" & pvtSht.Range("A3").Address(ReferenceStyle:=xlR1C1)
'Create Pivot Cache from Source Data
Set pvtCache = ActiveWorkbook.PivotCaches.Create( _
SourceType:=xlDatabase, _
SourceData:=SrcData)
'Create Pivot table from Pivot Cache
Set pvt = pvtCache.CreatePivotTable( _
TableDestination:=StartPvt, _
TableName:="P1")
'Insert Row Fields
With ActiveSheet.PivotTables("P1").PivotFields(" Vulnerability Name")
.Orientation = xlRowField
.Position = 1
End With
With ActiveSheet.PivotTables("P1").PivotFields(" DNS Name")
.Orientation = xlRowField
.Position = 2
End With
With ActiveSheet.PivotTables("P1").PivotFields(" Operating System")
.Orientation = xlRowField
.Position = 3
End With
With ActiveSheet.PivotTables("P1")
.AddDataField ActiveSheet.PivotTables( _
"P1").PivotFields("IP Address"), "Count of IP Addresses"
.PivotFields("IP Address").Orientation = xlRowField
End With
With Sheets("PivotTable").PivotTables("P1").PivotFields("IP Address")
.Orientation = xlRowField
.Position = 2
End With
Set pf = ActiveSheet.PivotTables("P1").PivotFields(" Vulnerability Name")
'Collapse Pivot Field
pf.ShowDetail = True
'Expand Pivot Field
pf.ShowDetail = False
'Create a new worksheet
Set summarySht = Sheets.Add
ActiveSheet.Name = "Summary"
End Sub
This is what it outputs on the Pivot Table sheet:
This is what I need it to output (Notice Risk Rating under Filters):
This is what needs to be displayed on the sheet:
Try like this
With ActiveSheet.PivotTables("P1").PivotFields("Risk Rating")
.Orientation = xlPageField
.Position = 1
End With
Not related to your error you are raising here, but just a notice to shorten your code a lot (and make it clearer to read):
You already Set your PivotTable so nicely here:
Set pvt = pvtCache.CreatePivotTable( _
TableDestination:=StartPvt, _
TableName:="P1")
So why not use it, and make the rest of your PivotTable settings like this:
With pvt
With .PivotFields(" Vulnerability Name")
.Orientation = xlRowField
.Position = 1
End With
With .PivotFields(" DNS Name")
.Orientation = xlRowField
.Position = 2
End With
With .PivotFields(" Operating System")
.Orientation = xlRowField
.Position = 3
End With
.AddDataField .PivotFields("IP Address"), "Count of IP Addresses"
.PivotFields("IP Address").Orientation = xlRowField
With .PivotFields("IP Address")
.Orientation = xlRowField
.Position = 2
End With
Set pf = .PivotFields(" Vulnerability Name")
End With

VBA code for creating Pivot Table

I have created a macro that builds a pivot table. It runs great but I want to dismiss the circled content in the screenshot provided .. I dont want to have the total inside the pivot. Only at the bottom the Grand Total! I am providing my code and a screenshot. Moreover, is it possible to substitute the "Row Labels" text in column B with "FDD"?
Sub aa()
'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("Customs_report").Delete
Sheets.Add Before:=ActiveSheet
ActiveSheet.Name = "Customs_report"
Application.DisplayAlerts = True
Set PSheet = Worksheets("Customs_report")
Set DSheet = Worksheets("Zeikan")
'Define Data Range
LastRow = DSheet.Cells(Rows.Count, 1).End(xlUp).Row
LastCol = DSheet.Cells(6, Columns.Count).End(xlToLeft).Column
Set PRange = DSheet.Cells(6, 1).Resize(LastRow, LastCol)
'Define Pivot Cache
Set PCache = ActiveWorkbook.PivotCaches.Create _
(SourceType:=xlDatabase, SourceData:=PRange). _
CreatePivotTable(TableDestination:=PSheet.Cells(2, 2), _
TableName:="PivotTable")
'Insert Blank Pivot Table
Set PTable = PCache.CreatePivotTable _
(TableDestination:=PSheet.Cells(1, 1), TableName:="PivotTable")
'Insert Row Fields
With ActiveSheet.PivotTables("PivotTable").PivotFields("Commodity Code")
.Orientation = xlRowField
.Position = 1
.Name = "Commodity Code"
End With
With ActiveSheet.PivotTables("PivotTable").PivotFields("Location")
.Orientation = xlRowField
.Position = 2
End With
'Insert Column Fields
With ActiveSheet.PivotTables("PivotTable").PivotFields("Quantity (cases/sw)")
.Orientation = xlDataField
.Position = 1
.Function = xlSum
.Name = "Sum of Quantity (cases/sw)"
End With
With ActiveSheet.PivotTables("PivotTable").PivotFields("Quantity (items)")
.Orientation = xlDataField
.Position = 2
.Function = xlSum
.Name = "Sum of Quantity (items)"
End With
With ActiveSheet.PivotTables("PivotTable").PivotFields("Net value")
.Orientation = xlDataField
.Position = 3
.Function = xlSum
.Name = "Sum of Net value"
End With
With ActiveSheet.PivotTables("PivotTable").PivotFields("Gross weight (Kg)")
.Orientation = xlDataField
.Position = 4
.Function = xlSum
.Name = "Sum of Gross weight (Kg)"
End With
With ActiveSheet.PivotTables("PivotTable").PivotFields("Net weight (Kg)")
.Orientation = xlDataField
.Position = 5
.Function = xlSum
.Name = "Sum of Net weight (Kg)"
End With
End Sub
You can toggle the subtotals:
With PTable.PivotFields("Commodity Code")
.Orientation = xlRowField
.Position = 1
.Name = "Commodity Code"
.Subtotals(1) = True
.Subtotals(1) = False
End With
to change the header, change the table layout to tabular
PTable.LayoutRowDefault = xlTabularRow
before you add the fields. BTW, you should be using PTable rather than ActiveSheet.PivotTables("PivotTable") in the rest of your code.

vba to create a pivot table excel 2015

I wanted to create a Pivot table in Excel 2015.
I recorded the macros to create my own vba code. But I couldn't make it. Also, I referred the links available here, but I couldn't make it out from them because they followed other way, which was hard for me.
Could anyone help me to frame the VBA code for the below recorded macros and explain in the comment the steps? This would be really helpful for me as I am generating the Pivot table in vba for first time.
Sub Macro4()
'
' Macro4 Macro
'
'
Cells.Select
Sheets.Add
ActiveWorkbook.PivotCaches.Create(SourceType:=xlDatabase, SourceData:= _
"Preparation sheet!R1C1:R1048576C8", Version:=xlPivotTableVersion15). _
CreatePivotTable TableDestination:="Sheet21!R3C1", TableName:="PivotTable7" _
, DefaultVersion:=xlPivotTableVersion15
Sheets("Sheet21").Select
Cells(3, 1).Select
With ActiveSheet.PivotTables("PivotTable7").PivotFields("Category")
.Orientation = xlRowField
.Position = 1
End With
With ActiveSheet.PivotTables("PivotTable7").PivotFields("Colour")
.Orientation = xlColumnField
.Position = 1
End With
With ActiveSheet.PivotTables("PivotTable7").PivotFields("Category")
.PivotItems("DG-035583").Visible = False
.PivotItems("DG-048917").Visible = False
.PivotItems("DG-Series").Visible = False
.PivotItems("gn").Visible = False
.PivotItems("yl").Visible = False
.PivotItems("(blank)").Visible = False
End With
With ActiveSheet.PivotTables("PivotTable7").PivotFields("Colour")
.PivotItems("(blank)").Visible = False
End With
End Sub
Try the code below to create/update a PivotTable, explanations inside the code as comments:
Option Explicit
Sub AutoPivot()
Dim PvtCache As PivotCache
Dim PvtTbl As PivotTable
Dim PvtSht As Worksheet
' set Pivot Cache for Pivot Table
' Your range is static, there are ways to refer to a dynamic range
Set PvtCache = ActiveWorkbook.PivotCaches.Create(SourceType:=xlDatabase, SourceData:="Preparation sheet!R1C1:R1048576C8")
' set the Pivot table's sheet
Set PvtSht = Worksheets("Sheet21")
' add this line in case the Pivot table doesn't exit >> first time running this Macro
On Error Resume Next
Set PvtTbl = PvtSht.PivotTables("PivotTable7") ' check if "PivotTable7" Pivot Table already created (in past runs of this Macro)
On Error GoTo 0
If PvtTbl Is Nothing Then ' Pivot table object is nothing >> create it
' create a new Pivot Table in "PivotTable4" sheet
Set PvtTbl = PvtSht.PivotTables.Add(PivotCache:=PvtCache, TableDestination:=PvtSht.Range("A3"), TableName:="PivotTable7")
With PvtTbl
With .PivotFields("Category")
.Orientation = xlRowField
.Position = 1
End With
With .PivotFields("Colour")
.Orientation = xlColumnField
.Position = 1
End With
With .PivotFields("Category")
.PivotItems("DG-035583").Visible = False
.PivotItems("DG-048917").Visible = False
.PivotItems("DG-Series").Visible = False
.PivotItems("gn").Visible = False
.PivotItems("yl").Visible = False
.PivotItems("(blank)").Visible = False
End With
With .PivotFields("Colour")
.PivotItems("(blank)").Visible = False
End With
End With
Else
' just refresh the Pivot cache with the updated Range
PvtTbl.ChangePivotCache PvtCache
PvtTbl.RefreshTable
End If
End Sub

Error while creating PivotTable

I am writing a code to create an Pivot table. I recorded the macros, and then simplified it to easy understanding.
While executing the code, I get error
subscript out of range.
I checked with the worksheet name, it is the same name I have defined.
I'm clueless, why it is not working. Below, is the code I tried.
Sub table()
Dim pvtcache As PivotCache
Dim pvttbl As pivottable
Dim pvtsht As Worksheet
Set pvtcache = ActiveWorkbook.PivotCaches.Create(SourceType:=xlDatabase, SourceData:= _
"Preparation Sheet!R1C1:R1048576C9")
Set pvtsht = Worksheets("LP")
On Error Resume Next
Set pvttbl = pvtsht.PivotTables("PivotTable3")
On Error GoTo 0
If pvttbl Is Nothing Then
Set pvttbl = pvtsht.PivotTables.Add(PivotCache:=pvtcache, TableDestination:=pvtsht.Range("A3"), TableName:="PivotTable3")
With pvttbl
With .PivotFields("DL")
.Orientation = xlRowField
.Position = 1
End With
With .PivotFields("Colour")
.Orientation = xlColumnField
.Position = 1
End With
End With
Else
' just refresh the Pivot cache with the updated Range
pvttbl.ChangePivotCache pvtcache
End If
End Sub
below is the code, from macros
Sub Macro8()
Sheets.Add
ActiveWorkbook.PivotCaches.Create(SourceType:=xlDatabase, SourceData:= _
"Preparation Sheet!R1C1:R1048576C9", Version:=xlPivotTableVersion15). _
CreatePivotTable TableDestination:="Sheet4!R3C1", TableName:="PivotTable2" _
, DefaultVersion:=xlPivotTableVersion15
Sheets("Sheet4").Select
Cells(3, 1).Select
With ActiveSheet.PivotTables("PivotTable2").PivotFields("DL")
.Orientation = xlRowField
.Position = 1
End With
ActiveSheet.PivotTables("PivotTable2").AddDataField ActiveSheet.PivotTables( _
"PivotTable2").PivotFields("Colour"), "Count of Colour", xlCount
With ActiveSheet.PivotTables("PivotTable2").PivotFields("Colour")
.Orientation = xlColumnField
.Position = 1
End With
End Sub
If your worksheet names contain spaces "Preparation Sheet!R1C1:R1048576C9" you need to enclose the worksheet name in ''
"'Preparation Sheet'!R1C1:R1048576C9"
or avoid spaces in it.
Edit
Add this function to your module
Public Function PivotTableExistsInWorksheet(pvWorksheet As Worksheet, pvTableName As String) As Boolean
Dim pvTable As PivotTable
PivotTableExistsInWorksheet = False 'Default
For Each pvTable In pvWorksheet.PivotTables
If pvTable.Name = pvTableName Then
PivotTableExistsInWorksheet = True
Exit Function
End If
Next pvTable
End Function
and use
If PivotTableExistsInWorksheet(pvtsht, "PivotTable3") Then
Set pvttbl = pvtsht.PivotTables("PivotTable3")
End If
instead of the On Error Resume Next … Goto 0 block to see if this works.