VBA-PIVOT TABLE WIZARD METHOD - excel

I am trying to create a macro to build pivottable using the code at the following website:
http://msdn.microsoft.com/en-us/library/office/hh243933.aspx
but I kept getting
Error 1004: "UNABLE TO GET THE PIVOTFIELDS PROPERTY OF THE PIVOT TABLE
CLASS"
Any suggestions on the reason behind this problem and possible ways to fix it?
THIS IS MY CODE:
Sub CreatePivot()
' Creates a PivotTable report from the table on Sheet1
' by using the PivotTableWizard method with the PivotFields
' method to specify the fields in the PivotTable.
Dim objTable As PivotTable, objField As PivotField
' Select the sheet and first cell of the table that contains the data.
ActiveWorkbook.Sheets("Sheet1").Select
Range("A2").Select
' Create the PivotTable object based on the Employee data on Sheet1.
Set objTable = Sheet1.PivotTableWizard
' Specify row and column fields.
***Set objField = objTable.PivotFields("v1")*** ' <-- This where I get the Error
objField.Orientation = xlColumnField
Set objField = objTable.PivotFields("Temperature")
objField.Orientation = xlRowField
' Specify a data field with its summary
' function and format.
Set objField = objTable.PivotFields("clkui")
objField.Orientation = xlDataField
objField.Function = xlSum
objField.NumberFormat = "$ #,##0"
' Specify a page field.
Set objField = objTable.PivotFields("db")
objField.Orientation = xlPageField
' Preview the new PivotTable report.
ActiveSheet.PrintPreview
' Prompt the user whether to delete the PivotTable.
Application.DisplayAlerts = False
If MsgBox("Delete the PivotTable?", vbYesNo) = vbYes Then
ActiveSheet.Delete
End If
Application.DisplayAlerts = True
End Sub
enter image description here

Try the code below to create a new table in Sheet1 (not sure what's the sheet's name) from the data in "Sheet1" :
Option Explicit
Sub CreatePivot()
' Creates a PivotTable report from the table on Sheet1
' by using the PivotTableWizard method with the PivotFields
' method to specify the fields in the PivotTable.
Dim objTable As PivotTable
Dim objTblCache As PivotCache
Dim objField As PivotField
Dim PvtSht As Worksheet
Dim LastRow As Long, LastCol As Long
Dim SrcRng As Range
' Select the sheet and first cell of the table that contains the data
With ThisWorkbook.Sheets("Sheet1")
LastRow = .Cells(.Rows.Count, "A").End(xlUp).Row
LastCol = .Cells(2, .Columns.Count).End(xlToLeft).Column
Set SrcRng = .Range(.Cells(2, "A"), .Cells(LastRow, LastCol)) ' <-- set the Pivot's dynamic Range (starts from "A2")
End With
' Option 1: Define Pivot Cache
Set objTblCache = ActiveWorkbook.PivotCaches.Create(xlDatabase, SrcRng)
' Option 2: Define Pivot Cache
Set objTblCache = ActiveWorkbook.PivotCaches.Create(SourceType:=xlDatabase, SourceData:=SrcRng.Address(True, True, xlA1, True))
' Create the PivotTable object based on the Employee data on Sheet1.
Set objTable = Sheet1.PivotTables.Add(PivotCache:=objTblCache, TableDestination:=Sheet1.Cells(1, LastCol + 2), TableName:="PivotTable1")
' Specify row and column fields.
With objTable
.PivotFields("v1").Orientation = xlColumnField
.PivotFields("Temperature").Orientation = xlRowField
' Specify a data field with its summary
' function and format.
Set objField = .PivotFields("clkui")
With objField
.Orientation = xlDataField
.Function = xlSum
.NumberFormat = "$ #,##0"
End With
' Specify a page field.
.PivotFields("db").Orientation = xlPageField
End With
' rest of your code goes here ....
End Sub

Related

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

Create Pivot Table Based on Dynamic Range

I am trying to create a macro that will take data that starts at A18, find the last row and last column then generate a pivot table. I searched around to take bits and pieces from code I found online to try to make something work.
I keep getting a 1004 error, and I suspect it is because my code isn't actually selecting the data range properly.
this is the code that the error happens on:
Set pvtable = pvcache.CreatePivotTable(TableDestination:=pvsheet.Cells(1, 1), TableName:="Payroll")
this is all of the code:
Dim pvtable As PivotTable
Dim pvcache As PivotCache
Dim ptrange As Range
Dim pvsheet As Worksheet
Dim pdsheet As Worksheet
Dim plr As Long
Dim plc As Long
Dim startCell As Range
On Error Resume Next
Application.DisplayAlerts = False
Application.ScreenUpdating = False
Worksheets("Pivot table").Delete 'to delete the existing pivot table in the worksheet
Worksheets.Add After:=ActiveSheet ' to add a new worksheet
ActiveSheet.Name = "Pivot Table" ' to rename the worksheet
On Error GoTo 0
Set pvsheet = Worksheets("Pivot table")
Set pdsheet = Worksheets("sheet1")
Set startCell = Range("A18")
'two variable to find Last used row and column in sheet 1, raw data'
plr = pdsheet.Cells(pdsheet.Rows.Count, startCell.Column).End(xlUp).Row
plc = pdsheet.Cells(startCell.Row, pdsheet.Columns.Count).End(xlToLeft).Column
'set range from selected data
Set ptrange = pdsheet.Cells(1, 1).Resize(plr, plc)
'pivot cahe needed for data load
Set pvcache = ActiveWorkbook.PivotCaches.Create(xlDatabase, SourceData:=ptrange)
'create empty pivot table
Set pvtable = pvcache.CreatePivotTable(TableDestination:=pvsheet.Cells(1, 1), TableName:="Payroll")
'Insert worker to Row Filed
With pvsheet.PivotTables("Payroll").PivotFields("Worker")
.Orientation = xlRowField
.Position = 1
End With
'Insert Street to Row Filed & position 2
With pvsheet.PivotTables("Payroll").PivotFields("Actual Hours")
.Orientation = xlRowField
.Position = 2
End With
'to show the pivot table in Tabular form
pvsheet.PivotTables("Payroll").RowAxisLayout xlTabularRow
Application.DisplayAlerts = True
Application.ScreenUpdating = True
End Sub
I am suspecting the issue is within this area here where the data range is selected to make the pivot table:
Set pvsheet = Worksheets("Pivot table")
Set pdsheet = Worksheets("sheet1")
Set startCell = Range("A18")
'two variable to find Last used row and column in sheet 1, raw data'
plr = pdsheet.Cells(pdsheet.Rows.Count, startCell.Column).End(xlUp).Row
plc = pdsheet.Cells(startCell.Row, pdsheet.Columns.Count).End(xlToLeft).Column
'set range from selected data
Set ptrange = pdsheet.Cells(1, 1).Resize(plr, plc)
any help appreciated, thank you
Try defining your range as follows...
Set ptrange = pdsheet.Range(startCell, pdsheet.Cells(plr, plc))
Or, alternatively...
Set pdsheet = Worksheets("sheet1")
Set startCell = pdsheet.Range("A18")
With pdsheet
plr = .Cells(.Rows.Count, startCell.Column).End(xlUp).Row
plc = .Cells(startCell.Row, .Columns.Count).End(xlToLeft).Column
Set ptrange = .Range(startCell, .Cells(plr, plc))
End With

Runtime error 1004 : Unable to get the PivotTables property of the Worksheet class

I am new to Excel VBA and I am trying to create a pivot table using only Row Field with the following codes but encountered error 1004 and would need help de-bugging.
I've indicated the error occurrence on the codes right after the comments
//
'Macros above create a pivot cache and address to insert the new pivot table
//
for easy referencing.
Appreciate any help on this.
Sub getpivotUI2()
'**strong text**
' getpivotUI2 Macro
' Create PivotTable from Task_Sheet to filter duplicate bill (UI2)
'
Dim P2Sheet, TSheet As Worksheet
Dim P2Cache As PivotCache
Dim P2Table As PivotTable
Dim P2Range As Range
Dim L2Row, L2Col As Long
' Declaring the variables above
Set TSheet = Worksheets("Task_Sheet")
Set P2Sheet = Worksheets("pivot_UI2")
L2Row = TSheet.Cells(Rows.Count, 1).End(xlUp).Row
L2Col = TSheet.Cells(4, Columns.Count).End(xlToLeft).Column
Set P2Range = TSheet.Cells(4, 1).Resize(L2Row, L2Col)
'Macros above determine where the cursor is referenced
P2Sheet.Cells.Delete 'Removing all previous data the pivotTable worksheet
Set P2Cache = ActiveWorkbook.PivotCaches.Create _
(SourceType:=xlDatabase, SourceData:=P2Range)
Set P2Table = P2Cache.CreatePivotTable _
(TableDestination:=P2Sheet.Cells(3, 1), TableName:="PivotTableUI2")
'Macros above create a pivot cache and address to insert the new pivot table
With ActiveSheet.PivotTables("PivotTableUI2").PivotFields("UI2") '**<-- ERROR OCCURANCE**
.Orientation = xlRowField
.Position = 1
End With
With ActiveSheet.PivotTables("PivotTableUI2").PivotTables("PivotTableUI2").PivotFields("Count_UI2")
.Orientation = xlDataField
.Function = xlCount
.Name = "Count of UI2"
End With
With ActiveSheet.PivotTables("PivotTableUI2").PivotTables("PivotTableUI2").PivotFields("R Patient" & Chr(10) & "Count")
.Orientation = xlDataField
.Function = xlCount
.Name = "Count of R Patient"
End With
With ActiveSheet.PivotTables("PivotTableUI2").PivotTables("PivotTableUI2").PivotFields("PR Patient" & Chr(10) & "Count")
.Orientation = xlDataField
.Function = xlCount
.Name = "Count of PR Patient"
End With
'Macros above inserts a row field and data field in the pivot table
End Sub
Try the code below, explanation inside the code's comments
Option Explicit
Sub getpivotUI2()
' getpivotUI2 Macro
' Create PivotTable from Task_Sheet to filter duplicate bill (UI2)
Dim P2Sheet As Worksheet, TSheet As Worksheet
Dim P2Cache As PivotCache
Dim P2Table As PivotTable
Dim P2Range As Range
Dim L2Row As Long, L2Col As Long
' Declaring the variables above
Set TSheet = ThisWorkbook.Worksheets("Task_Sheet")
Set P2Sheet = ThisWorkbook.Worksheets("pivot_UI2")
With TSheet
L2Row = .Cells(.Rows.Count, 1).End(xlUp).Row
L2Col = .Cells(4, .Columns.Count).End(xlToLeft).Column
Set P2Range = .Range(.Cells(4, 1), .Cells(L2Row, L2Col)) ' set the data source of the Pivot-Cache
End With
'Macros above determine where the cursor is referenced
P2Sheet.Cells.Delete 'Removing all previous data the pivotTable worksheet
' set the Pivot-Cache object
Set P2Cache = ActiveWorkbook.PivotCaches.Add(xlDatabase, P2Range.Address(0, 0, xlA1, xlExternal))
' set the Pivot-Table object
Set P2Table = P2Sheet.PivotTables.Add(PivotCache:=P2Cache, TableDestination:=P2Sheet.Range("A3"), TableName:="PivotTableUI2")
'Macros above create a pivot cache and address to insert the new pivot table
' ~~~ For Debug Only ~~~
Dim PTFld As PivotField
For Each PTFld In P2Table.PivotFields
Debug.Print PTFld.Name
Next PTFld
With P2Table.PivotFields("UI2")
.Orientation = xlRowField
.Position = 1
End With
' rest of your Pivot-Fields code ā€¦
End Sub
I've added a section in the Sub above that makes sure your Pivot-Table has a field "U12".
When you run this part:
' ~~~ For Debug Only ~~~
Dim PTFld As PivotField
For Each PTFld In P2Table.PivotFields
Debug.Print PTFld.Name
Next PTFld
You should get the following value in the immediate window:

VBA -Place Pivot Table in Same worksheet

New to VBA and I am having difficulty with my Macro creating a pivot table on the same worksheet with my data (for example, starting the pivot table in the "I1" column). I have been able to run the macro to select all of the data within the sheet and then create this data on another worksheet. Since I will need to loop through a number of worksheets on the same workbook to create multiple pivot tables, having separate sheets isn't feasible.
Each worksheet has the same number of columns with a varying number of rows. My goal is to have this macro look at each worksheet and output a pivot table next to it.
I feel like the macro I have below is not referencing the correct pivot Table destination. Any assistance would be appreciated.
Sub Macro4()
'
'Macro4 Macro
'
'
FinalRow = Cells(Rows.Count, 1).End(xlUp).Row
DataSheet = ActiveSheet.Name
ActiveWorkbook.PivotCaches.Create(SourceType:=xlDatabase, SourceData:= _
DataSheet & "!R1C1:R" & FinalRow & "C8", Version:=xlPivotTableVersion15). _
CreatePivotTable TableDestination:=DataSheet & "!R1C9", TableName:= _
"PivotTable4", DefaultVersion:=xlPivotTableVersion15
Sheets(DataSheet).Select
Cells(1, 9).Select
With ActiveSheet.PivotTables("PivotTable4").PivotFields("Document Type")
.Orientation = xlRowField.Position = 1
End With
With ActiveSheet.PivotTables("PivotTable4").PivotFields("Accounting Event")
.Orientation = xlRowField.Position = 2
End With
With ActiveSheet.PivotTables("PivotTable4").PivotFields("Document Number")
.Orientation = xlRowField.Position = 3
End With
ActiveSheet.PivotTables("PivotTable4").AddDataField ActiveSheet.PivotTables
( _"PivotTable4").PivotFields("Amount"), "Sum of Amount", xlSum
End Sub
Try the code below, it's with a little different approach, defining Range, PivotTable, PivotCache, and you can modify them easily according to your needs:
Sub Macro4()
Dim FinalRow As Long
Dim DataSheet As String
Dim PvtCache As PivotCache
Dim PvtTbl As PivotTable
Dim DataRng As Range
Dim TableDest As Range
FinalRow = Cells(Rows.Count, 1).End(xlUp).Row
DataSheet = ActiveSheet.Name
' set data range for Pivot Table
Set DataRng = Sheets(DataSheet).Range(Cells(1, 1), Cells(FinalRow, 8)) ' conversion of R1C1:R & FinalRow & C8
' set range for Pivot table placement
Set TableDest = Sheets(DataSheet).Cells(1, 9) ' conversion of R1C9
Set PvtCache = ActiveWorkbook.PivotCaches.Add(xlDatabase, DataRng)
' this line in case the Pivot table doesn't exit >> first time running this Macro
On Error Resume Next
Set PvtTbl = ActiveWorkbook.Sheets(DataSheet).PivotTables("PivotTable4") ' check if "PivotTable4" Pivot Table already created (in past runs of this Macro)
On Error GoTo 0
If PvtTbl Is Nothing Then ' "PivotTable4" doesn't exist >> create it
' create a new Pivot Table in "PivotTable4" sheet
Set PvtTbl = ActiveWorkbook.Sheets(DataSheet).PivotTables.Add(PivotCache:=PvtCache, TableDestination:=TableDest, TableName:="PivotTable4")
With PvtTbl.PivotFields("Document Type")
.Orientation = xlRowField
.Position = 1
End With
With PvtTbl.PivotFields("Accounting Event")
.Orientation = xlRowField
.Position = 2
End With
With PvtTbl.PivotFields("Document Number")
.Orientation = xlRowField
.Position = 3
End With
PvtTbl.AddDataField ActiveSheet.PivotTables( _
"PivotTable4").PivotFields("Amount"), "Sum of Amount", xlSum
Else
' just refresh the Pivot cache with the updated Range
PvtTbl.ChangePivotCache PvtCache
PvtTbl.RefreshTable
End If
End Sub

Excel VBA Pivot Table Wizard, set table destination and remove grand totals

The below works well, however I want the destination sheet to be a specific existing sheet called "PIVOT". Also I would like to remove grand totals for both rows and columns. Any ideas?
Sub CreatePivot()
' Creates a PivotTable report from the table on Sheet1
' by using the PivotTableWizard method with the PivotFields
' method to specify the fields in the PivotTable.
Dim objTable As PivotTable, objField As PivotField
' Select the sheet and first cell of the table that contains the data.
ActiveWorkbook.Sheets("DATA").Select
Range("A1").Select
' Create the PivotTable object based on the Employee data on Sheet1.
Set objTable = ActiveWorkbook.Sheets("DATA").PivotTableWizard
' Specify row and column fields.
Set objField = objTable.PivotFields("CCY")
objField.Orientation = xlRowField
Set objField = objTable.PivotFields("ACC")
objField.Orientation = xlRowField
Set objField = objTable.PivotFields("VD")
objField.Orientation = xlColumnField
' Specify a data field with its summary
' function and format.
Set objField = objTable.PivotFields("AMOUNT")
objField.Orientation = xlDataField
objField.Function = xlSum
objField.NumberFormat = "#,##0"
End Sub
The destination sheet can be defined by the TableDestination parameter of PivotTableWizard, then you can remove the grand totals with: ColumnGrand and RowGrand. Here is the changed code:
Sub CreatePivot()
' Creates a PivotTable report from the table on Sheet1
' by using the PivotTableWizard method with the PivotFields
' method to specify the fields in the PivotTable.
Dim objTable As PivotTable, objField As PivotField
' Select the sheet and first cell of the table that contains the data.
ActiveWorkbook.Sheets("DATA").Select
Range("A1").Select
' Create the PivotTable object based on the Employee data on PIVOT with the name 'PivotTableName'.
Set objTable = ActiveWorkbook.Sheets("DATA").PivotTableWizard(TableDestination:="PIVOT!R1C1", TableName:="PivotTableName")
'Remove grand totals
With Sheets("PIVOT").PivotTables("PivotTableName")
.ColumnGrand = False
.RowGrand = False
End With
' Specify row and column fields.
Set objField = objTable.PivotFields("CCY")
objField.Orientation = xlRowField
Set objField = objTable.PivotFields("ACC")
objField.Orientation = xlRowField
Set objField = objTable.PivotFields("VD")
objField.Orientation = xlColumnField
' Specify a data field with its summary
' function and format.
Set objField = objTable.PivotFields("AMOUNT")
objField.Orientation = xlDataField
objField.Function = xlSum
objField.NumberFormat = "#,##0"
End Sub

Resources