Pivot Table error whilecreating using VBA - excel

Good mrng!
I am trying to create pivot table using vba and i am very new to pivot using vba and i tried to research in google as much as possible to get this corrected but didnt find much info which can help me to fix it, would be of great help if anyone can help me with this.
Range - always starts from A10, columns will be fixed until H but number of rows are not fixed hence i tried to define the range and use it in the code but its throwing me below error message, please check and correct me
Issues faced-Not able to define Rng as Range and not able to use this range in the pivot table.
Rng as Range
Run time error '91': Object variable or with black variance not set
Pivot cache
Run Time error '438': Object doesn't support this property or method
Data
ACT AN Currency CB LC Type CB FC Type SI
1001 c USD 2,031 Dr 2,031 Dr 0005
1002 a BHD 1,194 Dr 1,194 Dr 0105
1003 P EUR 326 Dr 326 Dr 0110
1004 AR GBP 60,467 Dr 60,467 Dr 0125
1005 AP DHS (73,080) Cr (73,080) Cr 0190
Sub Pivot()
Dim ws As Worksheet
Dim pc As PivotCache
Dim pt As PivotTable
'Dim Rng As Range
'Defining Range
Rng = Range("A10").Select
Rng = Range(Selection, Selection.End(xlToRight)).Select
Rng = Range(Selection, Selection.End(xlDown)).Select
'Adding new worksheet
Set ws = Worksheets.Add
'Creating Pivot cache
Set pc = ActiveWorkbook.PivotCaches.Create(xlDatabase, "Working!Rng").Select
'Creating Pivot table
Set pt = pc.CreatePivotTable(ws.Range("B3"))
'Setting Fields
With pt
'set row field
With .PivotFields("SI")
.Orientation = xlRowField
.Position = 1
End With
'set column field
With .PivotFields("Currency")
.Orientation = xlColumnField
.Position = 1
End With
End With
End Sub
Thanks for your help!
Regards
Suresh7860

Try and use the below code as a sample for what you need. If anything is unclear I will be happy to answer. But you won't learn if I write the code for you.
Sub BuildPT()
Dim pvtTbl As PivotTable
Dim pvtCha As PivotCache
Dim pvtDestWS As Worksheet
Dim pvtSrcWS As Worksheet
Dim pvtWB As Workbook
Dim pvtSrcRng As Range
Dim pvtStrt As Range
Dim keyRng As Range
Dim LastRow As Integer
Dim LastCol As Integer
Application.ScreenUpdating = False
Application.Calculation = xlCalculationManual
On Error Resume Next
pvtWB.Worksheets("Total").Delete 'Delete PT destination sheet
On Error GoTo 0
Set pvtSrcWS = pvtWB.Worksheets("Data") 'Set source sheet name
'Here I find the last row and column containing data
LastRow = pvtSrcWS.Cells.Find(What:="*", After:=pvtSrcWS.Range("A1"), LookIn:=xlValues, LookAt:=xlWhole, SearchOrder:=xlByRows, SearchDirection:=xlPrevious, MatchCase:=False, MatchByte:=False).row
LastCol = pvtSrcWS.Cells.Find(What:="*", After:=pvtSrcWS.Range("A1"), LookIn:=xlValues, LookAt:=xlWhole, SearchOrder:=xlByColumns, SearchDirection:=xlPrevious, MatchCase:=False, MatchByte:=False).Column
Set pvtSrcRng = Range(pvtSrcWS.Cells(1, 3), pvtSrcWS.Cells(LastRow, LastCol)) 'Set the range that contains the source data
Set pvtDestWS = pvtWB.Sheets.Add 'Add the destination sheet
pvtDestWS.Name = "Total" 'Rename destination sheet
Set pvtStrt = pvtDestWS.Cells(1, 1) 'Set the PT start location
'Here I create the pivot cache, the container that holds pivot table data
'Then I create the pivot table itself
Set pvtCha = pvtWB.PivotCaches.Create(xlDatabase, pvtSrcRng)
Set pvtTbl = pvtCha.CreatePivotTable(TableDestination:=pvtStrt, TableName:="Test PT")
'Now I add the fields I need
With pvtTbl
With .PivotFields("Amount")
.Orientation = xlDataField
.Function = xlSum
.NumberFormat = "#,##0"
End With
With .PivotFields("Account")
.Orientation = xlPageField
.CurrentPage = "513035"
End With
.PivotFields("Key").Orientation = xlRowField
.RepeatAllLabels xlRepeatLabels
End With
Application.ScreenUpdating = True
Application.Calculation = xlCalculationAutomatic
End Sub

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

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

Resources