Creating a pivot table in VBA - vba

I have an xlsm file with some VBA code in it. I basically have a folder with a lot of csv files in it. When I execute the VBA code in the xlsm file, it needs to loop through each csv file, select the data in it and then create a pivot table from the data and export the sheet with the pivot table into a fresh workbook.
It needs to be dynamic in the sense that the amount of data (rows) is not the same in each csv file, so it first needs to select the block of data and then create the pivotcaches etc.
My code fails when trying to create the pivot table. See below for the relevant code. This code kicks off the job to loop through each csv:
Sub RunBatch()
Dim Filename, Pathname As String
Dim wb As Workbook
Pathname = "\\troy\Anfield\Product & Risk Management\Muhammad\2014\PnL Attribution Reports\20140822\"
Filename = Dir(Pathname & "*.csv")
Do While Filename <> ""
Set wb = Workbooks.Open(Pathname & Filename)
CreatePivotTableSummary wb
wb.Close SaveChanges:=True
Filename = Dir()
Loop
End Sub
This code is the one that actually creates the pivot:
Sub CreatePivotTableSummary(wb As Workbook)
Dim WorkbookName As String
WorkbookName = wb.Name
wb.Activate
Set DataRange = Range(Selection, Selection.End(xlToRight))
Set DataRange = Range(Selection, Selection.End(xlDown))
Set OutputRange = Sheet2.Range("A3")
Sheets.Add
ActiveWorkbook.PivotCaches.Create(SourceType:=xlDatabase, SourceData:=DataRange, Version:=xlPivotTableVersion14).CreatePivotTable TableDestination:=OutputRange, TableName:=WorkbookName, DefaultVersion:=xlPivotTableVersion14
Sheet2.Select
With wb.ActiveSheet.PivotTables(WorkbookName)
.PivotFields("Portfolio").Orientation = xlRowField
.PivotFields("Portfolio").Position = 1
.PivotFields("TradePortfolio").Orientation = xlRowField
.PivotFields("TradePortfolio").Position = 2
.PivotFields("InstrType").Orientation = xlRowField
.PivotFields("InstrType").Position = 3
.AddDataField ActiveSheet.PivotTables(WorkbookName).PivotFields("TPL"), "Sum of TPL", xlSum
.AddDataField ActiveSheet.PivotTables(WorkbookName).PivotFields("ThTPL Deco"), "Sum of ThTPL Deco", xlSum
.AddDataField ActiveSheet.PivotTables(WorkbookName).PivotFields("Corr Attr"), "Sum of Corr Attr", xlSum
.AddDataField ActiveSheet.PivotTables(WorkbookName).PivotFields("Cr Attr"), "Sum of Cr Attr", xlSum
.AddDataField ActiveSheet.PivotTables(WorkbookName).PivotFields("Cross Effec"), "Sum of Cross Effec", xlSum
.AddDataField ActiveSheet.PivotTables(WorkbookName).PivotFields("FX Attr"), "Sum of FX Attr", xlSum
.AddDataField ActiveSheet.PivotTables(WorkbookName).PivotFields("Infl Attr"), "Sum of Infl Attr", xlSum
.AddDataField ActiveSheet.PivotTables(WorkbookName).PivotFields("IR Attr"), "Sum of IR Attr", xlSum
.AddDataField ActiveSheet.PivotTables(WorkbookName).PivotFields("Price Attr"), "Sum of Price Attr", xlSum
.AddDataField ActiveSheet.PivotTables(WorkbookName).PivotFields("Residual"), "Sum of Residual", xlSum
.AddDataField ActiveSheet.PivotTables(WorkbookName).PivotFields("Time Attr"), "Sum of Time Attr", xlSum
.AddDataField ActiveSheet.PivotTables(WorkbookName).PivotFields("Trd Attr"), "Sum of Trd Attr", xlSum
.AddDataField ActiveSheet.PivotTables(WorkbookName).PivotFields("Vol Attr"), "Sum of Vol Attr", xlSum
.AddDataField ActiveSheet.PivotTables(WorkbookName).PivotFields("YC Attr"), "Sum of YC Attr", xlSum
.PivotFields("Sum of TPL").NumberFormat = "#,##0"
.PivotFields("Sum of ThTPL Deco").NumberFormat = "#,##0"
.PivotFields("Sum of Corr Attr").NumberFormat = "#,##0"
.PivotFields("Sum of Cr Attr").NumberFormat = "#,##0"
.PivotFields("Sum of Cross Effec").NumberFormat = "#,##0"
.PivotFields("Sum of FX Attr").NumberFormat = "#,##0"
.PivotFields("Sum of Infl Attr").NumberFormat = "#,##0"
.PivotFields("Sum of IR Attr").NumberFormat = "#,##0"
.PivotFields("Sum of Price Attr").NumberFormat = "#,##0"
.PivotFields("Sum of Residual").NumberFormat = "#,##0"
.PivotFields("Sum of Time Attr").NumberFormat = "#,##0"
.PivotFields("Sum of Trd Attr").NumberFormat = "#,##0"
.PivotFields("Sum of Vol Attr").NumberFormat = "#,##0"
.PivotFields("Sum of YC Attr").NumberFormat = "#,##0"
.RowAxisLayout xlTabularRow
.TableStyle2 = "PivotStyleMedium2"
.PivotFields("InstrType").PivotFilters.Add Type:=xlValueDoesNotEqual, DataField:=ActiveSheet.PivotTables(WorkbookName).PivotFields("Sum of TPL"), Value1:=0
End With
End Sub
It fails at this point:
ActiveWorkbook.PivotCaches.Create(SourceType:=xlDatabase, SourceData:=DataRange, Version:=xlPivotTableVersion14).CreatePivotTable TableDestination:=OutputRange, TableName:=WorkbookName, DefaultVersion:=xlPivotTableVersion14
with the error:
Invalid procedure call or argument
Please can someone assist?
Thank you

Sometimes, we get this error when any data range does not have a column Header.
Check whether first row of your data range has some header for all columns.
Pivot table creation fails, if it could not find a column header.

Related

application defined or object defined error when creating calculated fields

ActiveSheet.PivotTables("PivotTable13").AddDataField ActiveSheet.PivotTables( _
"PivotTable13").PivotFields("OOS VALUE"), "Sum of OOS VALUE", xlSum
ActiveSheet.PivotTables("PivotTable13").AddDataField ActiveSheet.PivotTables( _
"PivotTable13").PivotFields("Sales"), "Sum of Sales", xlSum
ActiveSheet.PivotTables("PivotTable13").CalculatedFields.Add "OOS", _
"=OOS VALUE/Sales", True
ActiveSheet.PivotTables("PivotTable13").PivotFields("OOS").Orientation = _
xlDataField
With ActiveSheet.PivotTables("PivotTable13").PivotFields("Sum of OOS VALUE")
.NumberFormat = "?#,##0.00"
End With
With ActiveSheet.PivotTables("PivotTable13").PivotFields("Sum of Sales")
.NumberFormat = "?#,##0.00"
End With
With ActiveSheet.PivotTables("PivotTable13").PivotFields("Sum of OOS")
.NumberFormat = "0.00%"
End With
I am getting the application defined or object defined error at the part where the calculated field is made. what's wrong? i'm using the record a macro feature if that helps

Error while creating Pivot Table automatically

I have created a macro to create a table with some values via Index matches and general calculations. This table is located on the range("AA1:BA"&LastRow) --> I am writing LastRow because the lastrow changes daily. I want to create a pivot table which will be located in the cell(9,1) and will have as a source the initial table that I created.. I built the code that you see below, but it gives me an error saying that the PivotTable field name is not valid on the line :
Set PCache = ActiveWorkbook.PivotCaches.Create(SourceType:=xlDatabase, SourceData:=PRange).CreatePivotTable(TableDestination:=PSheet.Cells(2, 2), TableName:="PivotTable")
The entire code related to the Pivot Table is below.
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
Application.DisplayAlerts = False
Application.DisplayAlerts = True
Set PSheet = Worksheets("Budget_Report")
Set DSheet = Worksheets("Budget_Report")
LastRow = DSheet.Cells(Rows.Count, 27).End(xlUp).Row
LastCol = DSheet.Cells(1, Columns.Count).End(xlToLeft).Column
Set PRange = DSheet.Cells(1, 27).Resize(LastRow, LastCol)
Set PCache = ActiveWorkbook.PivotCaches.Create(SourceType:=xlDatabase, SourceData:=PRange)
Set PTable = PCache.CreatePivotTable(TableDestination:=PSheet.Cells(9, 1), TableName:="PivotTable")
With ActiveSheet.PivotTables("PivotTable").PivotFields("T-Lane")
.Orientation = xlRowField
.Position = 1
.Subtotals(1) = True
.Subtotals(1) = False
End With
With ActiveSheet.PivotTables("PivotTable").PivotFields("Monthly Cost FCST")
.Orientation = xlDataField
.Position = 1
.Function = xlSum
.Name = "Monthly Cost Forecast"
End With
With ActiveSheet.PivotTables("PivotTable").PivotFields("Monthly Vol FCST")
.Orientation = xlDataField
.Position = 2
.Function = xlSum
.Name = "Monthly Vol Forecast"
End With
With ActiveSheet.PivotTables("PivotTable").PivotFields("Monthly $/SU FCST")
.Orientation = xlDataField
.Position = 3
.Function = xlSum
.Name = "Monthly $/SU Forecast"
End With
With ActiveSheet.PivotTables("PivotTable").PivotFields("Monthly Cost Actuals")
.Orientation = xlDataField
.Position = 4
.Function = xlSum
.Name = "Monthly Cost Actual"
End With
With ActiveSheet.PivotTables("PivotTable").PivotFields("Monthly Vol Actuals")
.Orientation = xlDataField
.Position = 5
.Function = xlSum
.Name = "Monthly Vol Actual"
End With
With ActiveSheet.PivotTables("PivotTable").PivotFields("Monthly $/SU Actuals")
.Orientation = xlDataField
.Position = 6
.Function = xlSum
.Name = "Monthly $/SU Actual"
End With
The recorded macro that builds the Pivot Table is provided below (it has specific range not lastrow and lastcolumn of course)
ActiveWorkbook.PivotCaches.Create(SourceType:=xlDatabase, SourceData:="Budget_Report!R1C27:R279C53", Version:=6).CreatePivotTable TableDestination:="Budget_Report!R9C1", TableName:="PivotTable1", DefaultVersion:=6
Sheets("Budget_Report").Cells(9, 1).Select
With ActiveSheet.PivotTables("PivotTable1").PivotFields("T-Lane")
.Orientation = xlRowField
.Position = 1
End With
ActiveSheet.PivotTables("PivotTable1").AddDataField ActiveSheet.PivotTables("PivotTable1").PivotFields("Monthly Cost FCST"), "Monthly Cost Forecast", xlSum
ActiveSheet.PivotTables("PivotTable1").AddDataField ActiveSheet.PivotTables("PivotTable1").PivotFields("Monthly Vol FCST"), "Monthly Vol Forecast", xlSum
ActiveSheet.PivotTables("PivotTable1").AddDataField ActiveSheet.PivotTables("PivotTable1").PivotFields("Monthly $/SU FCST"), "Monthly $/SU Forecast", xlSum
ActiveSheet.PivotTables("PivotTable1").AddDataField ActiveSheet.PivotTables("PivotTable1").PivotFields("Monthly Cost Actuals"), "Monthly Cost Actual", xlSum
ActiveSheet.PivotTables("PivotTable1").AddDataField ActiveSheet.PivotTables("PivotTable1").PivotFields("Monthly Vol Actuals"), "Monthly Vol Actual", xlSum
ActiveSheet.PivotTables("PivotTable1").AddDataField ActiveSheet.PivotTables("PivotTable1").PivotFields("Monthly $/SU Actuals"), "Monthly $/SU Actual", xlSum
ActiveWorkbook.ShowPivotTableFieldList = False
When setting the PRange you can use Cells.SpecialCells method to set your range even though you don't always know what that end address will be as long as you're sure you won't have extra data somewhere below/beyond your target range.
It would look something like this:
Set PRange = DSheet.Range(DSheet.Cells(1, 27), DSheet.Cells.SpecialCells(xlCellTypeLastCell))
Also, it is a matter of personal style, but I find that nesting With blocks sometimes results in more readable code. Eg:
With ActiveSheet.PivotTables("PivotTable1")
With .PivotFields("Field 1")
.Caption = "My first field"
.Function = xlSum
End With
With .PivotFields("Field 2")
.Caption = "My second field"
.Function = xlMax
End With
End With
etc.
The final product looks something like this:
Dim DSheet As Worksheet ', PSheet As Worksheet
Dim PCache As PivotCache, PTable As PivotTable, PRange As Range
'Dim LastRow As Long, LastCol As Long
'Application.DisplayAlerts = False ' This is redundant since you're setting it to true below.
Application.DisplayAlerts = True
'Set PSheet = Worksheets("Budget_Report") '
Set DSheet = Worksheets("Budget_Report") ' These two are Redundant - I am using only DSheet.
'LastRow = DSheet.Cells(Rows.Count, 27).End(xlUp).Row
'LastCol = DSheet.Cells(1, Columns.Count).End(xlToLeft).Column
Set PRange = DSheet.Range(Cells(1, 27),Cells.SpecialCells(xlCellTypeLastCell))
Set PCache = ActiveWorkbook.PivotCaches.Create(SourceType:=xlDatabase, SourceData:=PRange)
Set PTable = PCache.CreatePivotTable(TableDestination:=DSheet.Cells(9, 1), TableName:="PivotTable")
With ActiveSheet.PivotTables("PivotTable")
With .PivotFields("T-Lane")
.Orientation = xlRowField
.Position = 1
.Subtotals(1) = True ' You're resetting this value in the next line, you can probably remove it.
.Subtotals(1) = False
End With
With .PivotFields("Monthly Cost FCST")
.Orientation = xlDataField
.Position = 1
.Function = xlSum
.Caption = "Monthly Cost Forecast" 'You want .Caption here, not .Name
End With
With .PivotFields("Monthly Vol FCST")
.Orientation = xlDataField
.Position = 2
.Function = xlSum
.Caption = "Monthly Vol Forecast"
End With
With .PivotFields("Monthly $/SU FCST")
.Orientation = xlDataField
.Position = 3
.Function = xlSum
.Caption = "Monthly $/SU Forecast"
End With
With .PivotFields("Monthly Cost Actuals")
.Orientation = xlDataField
.Position = 4
.Function = xlSum
.Caption = "Monthly Cost Actual"
End With
With .PivotFields("Monthly Vol Actuals")
.Orientation = xlDataField
.Position = 5
.Function = xlSum
.Caption = "Monthly Vol Actual"
End With
With .PivotFields("Monthly $/SU Actuals")
.Orientation = xlDataField
.Position = 6
.Function = xlSum
.Caption = "Monthly $/SU Actual"
End With
End With
It appears that you try to create the same table twice:
Set PCache = ActiveWorkbook.PivotCaches.Create(SourceType:=xlDatabase, SourceData:=PRange).CreatePivotTable(TableDestination:=PSheet.Cells(2, 2), TableName:="PivotTable")
Set PTable = PCache.CreatePivotTable(TableDestination:=PSheet.Cells(9, 1), TableName:="PivotTable")
Just split it in two:
Set PCache = ActiveWorkbook.PivotCaches.Create(SourceType:=xlDatabase, SourceData:=PRange)
Set PTable = PCache.CreatePivotTable(TableDestination:=PSheet.Cells(9, 1), TableName:="PivotTable")
Assign to PCache only Cache:
Set PCache = ActiveWorkbook.PivotCaches.Create(SourceType:=xlDatabase, SourceData:=PRange)

Generating Pivot for the last updated row

I have two sheets. Sheet1 "Result" which has an table that contains 8 columns.
I have the second sheet "Sum" where I am generating an Pivot table for the Reuslt sheet.
The code, works fine, but it calculates the sum of each and every column and gives the result.
I would like to have the pivot table only for the last updated row.
Each and everyweek the last update row changes. Next week ,the updates will be found in 17th and so on...
Could anyone suggest how I could do it? any lead would be helpful
Sub sum2017()
Dim ws9 As Worksheet
Dim pc9 As PivotCache
Dim pt9 As PivotTable
Dim ct9 As Integer
Set ws9 = Sheets("Sum")
Set pc9 = ActiveWorkbook.PivotCaches.Create(xlDatabase, "'Result'!R1C1:R1048576C6")
Set pt9 = pc9.CreatePivotTable(ws9.Range("A3"))
pt9.AddDataField pt9.PivotFields("NOK"), "Sum of NOK", xlSum
pt9.AddDataField pt9.PivotFields("OK"), "Sum of OK", xlSum
pt9.AddDataField pt9.PivotFields("Total"), "Sum of Total", xlSum
pt9.AddDataField pt9.PivotFields("NOK %"), "Sum of NOK %", xlSum
pt9.AddDataField pt9.PivotFields("OK %"), "Sum of OK %", xlSum
pt9.DataLabelRange.HorizontalAlignment = xlCenter
pt9.DataLabelRange.ReadingOrder = xlContext
pt9.TableRange2.HorizontalAlignment = xlCenter
End Sub
This code works, but every time will add help sheet when new pivottable is created. If you dont want to do that, just add some extra sheet, name it as you want to, than change referece of wskHelpSheet to that sheet and remember to always clean this worksheet at the start of your macro. I hope that it sound clear to you :)
Sub sum2017()
Dim ws9 As Worksheet
Dim wskResult As Worksheet
Dim pc9 As PivotCache
Dim pt9 As PivotTable
Dim ct9 As Integer
Dim rngPivotRangeHeaders As Range
Dim lngLRow As Long
Dim lngLCol As Long
Dim rngPivotRangeRecords As Range
Dim rngPTRange As Range
Dim wskHelpSheet As Worksheet
Set ws9 = Sheets("Sum")
Set wskResult = ThisWorkbook.Sheets("Result")
Set wskHelpSheet = Worksheets.Add
With wskResult
lngLRow = .Cells(Rows.Count, "B").End(xlUp).Row
lngLCol = .Cells(1, Columns.Count).End(xlToLeft).Column
Set rngPivotRangeHeaders = .Range(.Cells(1, 1), .Cells(1, lngLCol))
Set rngPivotRangeRecords = .Range(.Cells(lngLRow, 1), .Cells(lngLRow, lngLCol))
Set rngPTRange = Union(rngPivotRangeHeaders, rngPivotRangeRecords)
rngPTRange.Copy
End With
With wskHelpSheet
.Range("a1").PasteSpecial Paste:=xlPasteValues
lngLRow = .Cells(Rows.Count, "B").End(xlUp).Row
lngLCol = .Cells(1, Columns.Count).End(xlToLeft).Column
Set rngPTRange = .Range(.Cells(1, 1), .Cells(lngLRow, lngLCol))
End With
Set pc9 = ActiveWorkbook.PivotCaches.Create(xlDatabase, rngPTRange)
Set pt9 = pc9.CreatePivotTable(ws9.Range("A3"))
With pt9
.AddDataField .PivotFields("NOK"), "Sum of NOK", xlSum
.AddDataField .PivotFields("OK"), "Sum of OK", xlSum
.AddDataField .PivotFields("Total"), "Sum of Total", xlSum
.AddDataField .PivotFields("NOK %"), "Sum of NOK %", xlSum
.AddDataField .PivotFields("OK %"), "Sum of OK %", xlSum
.DataLabelRange.HorizontalAlignment = xlCenter
.DataLabelRange.ReadingOrder = xlContext
.TableRange2.HorizontalAlignment = xlCenter
End With
End Sub

How to make my pivot fields dynamic in vba code

I have a pivot table that sorts data for various people for each month over a 12-month period. The table that the data is generated from has a dynamic date range (ie the user can specify the start date which will cascade through the table). The pivot table and chart is generated from this master table as part of the data analysis.
This worked fantastic last month when I created this tool, however I realised in my code I have hard-coded names of the pivot fields to correspond to months from April (please see below). This makes my pivot table break when I try to run it from a start date in May. How can I make the "PivotFields"/data fields in the pivot table dynamic to correspond to the date range?
Relevant piece of the code found below. As one would expect, the error happens at:
"Compare individuals").PivotFields("Apr-17"), "Sum of Apr-17", xlSum
ActiveSheet.PivotTables("Compare individuals").AddDataField
When trying to run my pivot chart/report from May.
Really appreciate any pointers!
Option Explicit
Sub CreatePivot()
Dim pt As PivotTable
Dim pf As PivotField
Dim pi As PivotItem
Dim pc As PivotCache
With ActiveWorkbook
For Each pc In .PivotCaches
pc.MissingItemsLimit = xlMissingItemsNone
Next pc
End With
'Generate base pivot chart
ActiveWorkbook.PivotCaches.Create(SourceType:=xlDatabase, SourceData:= _
"Indy", Version:=xlPivotTableVersion10). _
CreatePivotTable TableDestination:="'PivotSheet'!R8C6", TableName:="Compare individuals" _
, DefaultVersion:=xlPivotTableVersion10
Worksheets("PivotSheet").Activate
'Set Name and disc as field and filter respectively
With ActiveSheet.PivotTables("Compare individuals").PivotFields("Name")
.Orientation = xlRowField
.Position = 1
End With
With ActiveSheet.PivotTables("Compare individuals").PivotFields("Disc ")
.Orientation = xlPageField
.Position = 1
End With
'Add data; sums of each month per individual
ActiveSheet.PivotTables("Compare individuals").AddDataField ActiveSheet.PivotTables( _
"Compare individuals").PivotFields("Apr-17"), "Sum of Apr-17", xlSum
ActiveSheet.PivotTables("Compare individuals").AddDataField ActiveSheet.PivotTables( _
"Compare individuals").PivotFields("May-17"), "Sum of May-17", xlSum
ActiveSheet.PivotTables("Compare individuals").AddDataField ActiveSheet.PivotTables( _
"Compare individuals").PivotFields("Jun-17"), "Sum of Jun-17", xlSum
ActiveSheet.PivotTables("Compare individuals").AddDataField ActiveSheet.PivotTables( _
"Compare individuals").PivotFields("Jul-17"), "Sum of Jul-17", xlSum
ActiveSheet.PivotTables("Compare individuals").AddDataField ActiveSheet.PivotTables( _
"Compare individuals").PivotFields("Aug-17"), "Sum of Aug-17", xlSum
ActiveSheet.PivotTables("Compare individuals").AddDataField ActiveSheet.PivotTables( _
"Compare individuals").PivotFields("Sep-17"), "Sum of Sep-17", xlSum
ActiveSheet.PivotTables("Compare individuals").AddDataField ActiveSheet.PivotTables( _
"Compare individuals").PivotFields("Oct-17"), "Sum of Oct-17", xlSum
ActiveSheet.PivotTables("Compare individuals").AddDataField ActiveSheet.PivotTables( _
"Compare individuals").PivotFields("Nov-17"), "Sum of Nov-17", xlSum
ActiveSheet.PivotTables("Compare individuals").AddDataField ActiveSheet.PivotTables( _
"Compare individuals").PivotFields("Dec-17"), "Sum of Dec-17", xlSum
ActiveSheet.PivotTables("Compare individuals").AddDataField ActiveSheet.PivotTables( _
"Compare individuals").PivotFields("Jan-18"), "Sum of Jan-18", xlSum
ActiveSheet.PivotTables("Compare individuals").AddDataField ActiveSheet.PivotTables( _
"Compare individuals").PivotFields("Feb-18"), "Sum of Feb-18", xlSum
ActiveSheet.PivotTables("Compare individuals").AddDataField ActiveSheet.PivotTables( _
"Compare individuals").PivotFields("Mar-18"), "Sum of Mar-18", xlSum
ActiveSheet.PivotTables("Compare individuals").PivotFields("Disc ").CurrentPage = _
"(All)"
'Set data in columns
With ActiveSheet.PivotTables("Compare individuals").DataPivotField
.Orientation = xlColumnField
.Position = 1
End With
EDIT: a bit more context.
My PivotTable looks like this:
The error ostensibly shows up because there's no "Apr-17" in the actual data table
My source data looks like this:
Wherein the months/date range are dynamic (from initial input).
What I want the code to do is this:
Ie put all the date columns into the table regardless of what they are called.
#A.Doe, give this a try
Dim f1 As PivotField
For Each f1 In ActiveSheet.PivotTables("Compare individuals").PivotFields
'MsgBox f1.Name test code
If (InStr(f1.Name, "17") > 0) Then 'or some valid condition
ActiveSheet.PivotTables("Compare individuals").AddDataField ActiveSheet.PivotTables( _
"Compare individuals").PivotFields(f1.Name), "Sum of " & f1.Name, xlSum
End If
Next

Excel VBA - Stuck on generating pivot table from variable data range

I have the code below which theoretically should create a pivot table on a 2nd sheet (which exists) using the data it finds on the 'DATA' sheet. However it always crashes as soon as it reaches the part to create the pivot table.
I originally come from a fixed size and afterwards changed it so it should take all the data on my 'DATA' sheet regardless of whether it's a 2x3 or 58x13 table
Sheets("DATA").Select
Range("H1").Select
ActiveCell.FormulaR1C1 = "l"
Range("A1").Select
ActiveWorkbook.PivotCaches.Create(SourceType:=xlDatabase, SourceData:= _
Sheets("DATA").Range("A1").CurrentRegion, _
Version:=xlPivotTableVersion14).CreatePivotTable _
TableDestination:="Prior. per user!R1C1", TableName:="PivotTable1", _
DefaultVersion:=xlPivotTableVersion14
Sheets("Prior. per user").Select
Cells(1, 1).Select
With ActiveSheet.PivotTables("PivotTable1").PivotFields("Priority")
.Orientation = xlColumnField
.Position = 1
End With
With ActiveSheet.PivotTables("PivotTable1").PivotFields("Caller")
.Orientation = xlRowField
.Position = 1
End With
Range("D2").Select
ActiveSheet.PivotTables("PivotTable1").PivotFields("Priority").PivotItems( _
"Medium").Position = 2
Columns("D:D").ColumnWidth = 7.43
Columns("C:C").ColumnWidth = 10
ActiveSheet.PivotTables("PivotTable1").AddDataField ActiveSheet.PivotTables( _
"PivotTable1").PivotFields("Number"), "Sum of Number", xlSum
With ActiveSheet.PivotTables("PivotTable1").PivotFields("Sum of Number")
.Caption = "Count of Number"
.Function = xlCount
End With
If anyone sees what's wrong with it, it would be much appreciated.
Your target sheet name has spaces in it so you need to enclose it in single quotes:
ActiveWorkbook.PivotCaches.Create(SourceType:=xlDatabase, SourceData:= _
Sheets("DATA").Range("A1").CurrentRegion, _
Version:=xlPivotTableVersion14).CreatePivotTable _
TableDestination:="'Prior. per user'!R1C1", TableName:="PivotTable1", _
DefaultVersion:=xlPivotTableVersion14
Personally, I would also use a variable to refer to the pivot table:
Dim PT As PivotTable
Set PT = ActiveWorkbook.PivotCaches.Create(SourceType:=xlDatabase, SourceData:= _
Sheets("DATA").Range("A1").CurrentRegion, _
Version:=xlPivotTableVersion14).CreatePivotTable(TableDestination:="'Prior. per user'!R1C1", TableName:="PivotTable1", _
DefaultVersion:=xlPivotTableVersion14)
With PT
With .PivotFields("Priority")
.Orientation = xlColumnField
.Position = 1
End With
With .PivotFields("Caller")
.Orientation = xlRowField
.Position = 1
End With
.PivotFields("Priority").PivotItems("Medium").Position = 2
.Parent.Columns("D:D").ColumnWidth = 7.43
.Parent.Columns("C:C").ColumnWidth = 10
.AddDataField .PivotFields("Number"), "Count of Number", xlCount
End With