I have been trying to create a macro that populates a pivot table. However, I keep getting this
Run-Time Error 440
on the Set Cache line.
Previously, I was running into other run time errors but those were easy fixes. I do not understand why the PivotCaches.Create method is not allowed in this case. SOS, please help!
Here is the code:
' Declare variables for pivots
Dim pivotWB As Workbook
Dim RawDataWS As Worksheet
Dim dataLocation As Range
Dim cache As PivotCache
Dim table As PivotTables
' name and set the workbook for pivot tables
folderName = ThisWorkbook.Sheets(1).Cells(5, 13).Value
fileName = ThisWorkbook.Sheets(1).Cells(6, 13).Value
extName = ThisWorkbook.Sheets(1).Cells(7, 13).Value
wbAddress = folderName & "\" & fileName & "." & extName
Set pivotWB = Workbooks.Open(wbAddress)
Set dataLocation = pivotWB.Sheets("Raw Data").Range("A:AK")
Set cache = pivotWB.PivotCaches.Create(SourceType:=xlDatabase,_
sourceData:=dataLocation, Version:=xlPivotTableVersion14)
For i = 1 To 5
' create new worksheet and pivot table
pivotWB.Sheets.Add Before:=Sheets(1)
pivotWB.Sheets(1).Name = Left(toPivot(i), 30)
cache.CreatePivotTable TableDestination:=pivotWB.Sheets(1).Cells(1, 1), TableName:=toPivot(i) & " Pivot Table"
' set rows
With pivotWB.Sheets(1).PivotTables(toPivot(i) & " Pivot Table").PivotFields("Rejection Category Description")
.Orientation = xlRowField
.Position = 1
End With
' set columns
With pivotWB.Sheets(1).PivotTables(toPivot(i) & " Pivot Table").PivotFields("Post Period")
.Orientation = xlColumnField
.Position = 1
End With
' set values
With pivotWB.Sheets(1).PivotTables(toPivot(i) & " Pivot Table").PivotFields("Procedure Code")
.Orientation = xlDataField
.Position = 1
.Function = xlCount
.NumberFormat = "#,##0"
.Name = "Count of Code"
End With
With pivotWB.Sheets(1).PivotTables(toPivot(i) & " Pivot Table").PivotFields("Amount")
.Orientation = xlDataField
.Position = 2
.Function = xlSum
.NumberFormat = "$#,##0"
.Name = "Sum of Amount"
End With
Next i
Following #Rory comment, you need to set the PivotCache object using the Address property.
Also, setting your table object to your PivotTable will create a much easier and shorter code.
See code below, more notes inside the code's comments.
Modified Code
' --- set the Pivot Cache ---
Set cache = pivotWB.PivotCaches.Create(SourceType:=xlDatabase, _
SourceData:=dataLocation.Address(False, False, xlR1C1, xlExternal))
For i = 1 To 5
' create new worksheet and pivot table
pivotWB.Sheets.Add Before:=Sheets(1)
pivotWB.Sheets(1).Name = Left(toPivot(i), 30)
' --- set the Pivot-Table Object ---
Set table = cache.CreatePivotTable(TableDestination:=pivotWB.Sheets(1).Cells(1, 1), TableName:=toPivot(i) & " Pivot Table")
With table ' <-- after you set the table object, you can simply use With statement now
' set rows
With .PivotFields("Rejection Category Description")
.Orientation = xlRowField
.Position = 1
End With
' set columns
With .PivotFields("Post Period")
.Orientation = xlColumnField
.Position = 1
End With
' set values
With .PivotFields("Procedure Code")
.Orientation = xlDataField
.Position = 1
.Function = xlCount
.NumberFormat = "#,##0"
.Name = "Count of Code"
End With
With .PivotFields("Amount")
.Orientation = xlDataField
.Position = 2
.Function = xlSum
.NumberFormat = "$#,##0"
.Name = "Sum of Amount"
End With
End With
Next i
Related
I'm trying to put two pivot tables into the same sheet but my second pivot table is not being created when I step into VBA. The code runs without any errors, but the second pivot table is never created. I'm looking to eventually add many pivot tables to the same sheet so any help with this would be appreciated.
I've tried setting two different caches, but I don't believe that will help solve this specific problem. I've also tried
Sub CreatePivottablewithVBA()
'Declare Variables
Dim Psheet As Worksheet
Dim DSheet As Worksheet
Dim PCache As PivotCache
Dim Ptable As PivotTable
Dim Ptable2 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("PivotTable").Delete
Sheets.Add After:=ActiveSheet
ActiveSheet.Name = "PivotTable"
Application.DisplayAlerts = True
Set Psheet = Worksheets("PivotTable")
Set DSheet = Worksheets("Raw")
'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:="SalesbyYearMonth")
'Insert Blank Pivot Table
Set Ptable = PCache.CreatePivotTable _
(TableDestination:=Psheet.Cells(1, 1), TableName:="SalesbyYearMonth")
'Insert Row Fields
With ActiveSheet.PivotTables("SalesbyYearMonth").PivotFields("ck_complete_dt")
.Orientation = xlRowField
.Position = 2
End With
'Insert Data Field
With ActiveSheet.PivotTables("SalesbyYearMonth").PivotFields("total_amount")
.Orientation = xlDataField
.Position = 1
.Function = xlCount
.Name = "# of Sales"
End With
With ActiveSheet.PivotTables("SalesbyYearMonth").PivotFields("total_amount")
.Orientation = xlDataField
.Position = 2
.NumberFormat = "$#,##0.00"
.Function = xlSum
.Name = "Total Amount"
End With
With ActiveSheet.PivotTables("SalesbyYearMonth").PivotFields("total_amount")
.Orientation = xlDataField
.Position = 3
.Calculation = xlPercentOfTotal
.NumberFormat = "0.00%"
.Name = "% of Total"
End With
'Format Pivot Table
ActiveSheet.PivotTables("SalesbyYearMonth").ShowTableStyleRowStripes = True
ActiveSheet.PivotTables("SalesbyYearMonth").TableStyle2 = "PivotStyleMedium9"
PivotTable.DataOnRows = False
'Create PivotTable2
Set Ptable2 = PCache.CreatePivotTable(TableDestination:=Psheet.Cells(22, 2), TableName:="SalesPerCategory")
With ActiveSheet.PivotTables("SalesPerCategory").PivotFields("highest_categ_level")
.Orientation = xlRowField
.Position = 1
.Name = "Category"
End With
With ActiveSheet.PivotTables("SalesPerCategory").PivotFields("highest_categ_level")
.Orientation = xlDataField
.Position = 1
.Function = xlSum
.Name = "Count of Categories"
End With
End Sub
I don't receive any error messages but I expect to see both pivot tables created in the sheet PivotTable
I am creating an 8th Pivot Table in the same spreadsheet and I am getting the following error for the LAST PIVOT TABLE:
"Run-time error '1004':
The PivotTable field name is not valid. To create a PivotTable report you must use data that is organized as a list of labeled columns. If you are changing the name of a PivotTable field, you must type a new name for the field.
"
However, I have tried to change the name of Pivot Table several times and the issue has not been resolved.
My code is as follows:
Sub Macro1()
'Pivot Table 8
'Declare Variables
Dim PSheet As Worksheet
Dim DSheet As Worksheet
Dim LastRow As String
Dim LastCol As String
Dim SData As String
Dim PCache As PivotCache
Dim PTable As PivotTable
Set PSheet = Worksheets("US MASTER")
Set DSheet = Worksheets("US Master Macro")
LastRow = DSheet.Cells(Rows.Count, 1).End(xlUp).Row
LastCol = DSheet.Cells(1, Columns.Count).End(xlToLeft).Column
SData = "'US Master Macro'!R1C1:R" & LastRow & "C" & LastCol
Set PCache = ActiveWorkbook.PivotCaches.Create _
(SourceType:=xlDatabase, SourceData:=SData)
Set PTable = PCache.CreatePivotTable(TableDestination:=Worksheets("US MASTER").Range("Y4"), TableName:="InfoView Cases")
With ActiveSheet.PivotTables("InfoView Cases")
.SmallGrid = False
'Add Days to Row Field
With .PivotFields("Age of Case")
.Orientation = xlRowField
.Position = 1
End With
'Add PR ID to Values Field
With .PivotFields("PR ID")
.Orientation = xlDataField
.Function = xlCount
.Position = 1
End With
'Add Filter
With .PivotFields("SAP Notification")
.Orientation = xlPageField
.Position = 1
End With
'Add Filter
With .PivotFields("Case Status")
.Orientation = xlPageField
.Position = 2
End With
End With
'Deselect Filter
l = ActiveSheet.PivotTables("InfoView Cases").PivotFields("SAP Notification"). _
PivotItems.Count - 1
For k = 1 To l
With ActiveSheet.PivotTables("InfoView Cases").PivotFields("SAP Notification")
.PivotItems(k).Visible = False
End With
Next k
With ActiveSheet.PivotTables("InfoView Cases").PivotFields("SAP Notification")
.PivotItems("(blank)").Visible = True
End With
'Deselect Filter
n = ActiveSheet.PivotTables("InfoView Cases").PivotFields("Case Status"). _
PivotItems.Count - 1
For m = 1 To n
With ActiveSheet.PivotTables("InfoView Cases").PivotFields("Case Status")
.PivotItems(m).Visible = False
End With
Next m
With ActiveSheet.PivotTables("InfoView Cases").PivotFields("Case Status")
.PivotItems("(blank)").Visible = True
End With
'Add InfoView Cases
PSheet.Range("Y3").Value = "InfoView Cases"
PSheet.Range("Y4").Value = "Days"
'Merge
PSheet.Range("Y3:Z3").Merge
'Sort Pivot Table
Range("Y5:Y100").Select
ActiveSheet.PivotTables("InfoView Cases").PivotFields("Age of Case").AutoSort _
xlAscending, "Age of Case"
End Sub
My code breaks in the line
Set PTable = PCache.CreatePivotTable(TableDestination:=Worksheets("US MASTER").Range("Y4"), TableName:="InfoView Cases")
This answer was provided by Mathieu Guindon:
Dim srcRange As Range
sTable = "DataTable"
Set ListObj = ActiveSheet.ListObjects.Add(xlSrcRange, [A1].CurrentRegion, , xlYes)
ListObj.Name = sTable 'The name for the table
ListObj.TableStyle = "TableStyleDark8"
Dim srcRange_s As String
srcRange_s = ActiveSheet.ListObjects("DataTable")
'Pivot Table 8
'Pivot Table 8
'Pivot Table 8
'Define Pivot Cache and Insert Pivot Table
Set PCache = ActiveWorkbook.PivotCaches.Create _
(SourceType:=xlDatabase, SourceData:=srcRange_s)
Set PTable = PCache.CreatePivotTable(Range("Y4"), TableName:="InfoView Cases")
'Add Fields
With ActiveSheet.PivotTables("InfoView Cases")
.SmallGrid = False
'Add Days to Row Field
With .PivotFields("Age of Case")
.Orientation = xlRowField
.Position = 1
End With
'Add PR ID to Values Field
With .PivotFields("PR ID")
.Orientation = xlDataField
.Function = xlCount
.Position = 1
End With
'Add Filter
With .PivotFields("SAP Notification")
.Orientation = xlPageField
.Position = 1
End With
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
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.
Im very new to VBA. I will explain my project.
I have an Excel sheet with a lot of information that I want to filter. For the moment my code looks like this:
With ActiveSheet.PivotTables("Tableau croisé dynamique2").PivotFields( _
"CREATION_DATE")
.Orientation = xlPageField
.Position = 1
End With
ActiveSheet.PivotTables("Tableau croisé dynamique2").AddDataField ActiveSheet. _
PivotTables("Tableau croisé dynamique2").PivotFields("AMOUNT"), _
"Nombre de AMOUNT", xlCount
With ActiveSheet.PivotTables("Tableau croisé dynamique2").PivotFields("STATUS")
.Orientation = xlRowField
.Position = 1
End With
With ActiveSheet.PivotTables("Tableau croisé dynamique2").PivotFields( _
"VENDOR_NAME")
.Orientation = xlRowField
.Position = 2
End With
With ActiveSheet.PivotTables("Tableau croisé dynamique2").PivotFields( _
"INVOICE_NUM")
.Orientation = xlRowField
.Position = 3
End With
With ActiveSheet.PivotTables("Tableau croisé dynamique2").PivotFields( _
"Nombre de AMOUNT")
.Caption = "Somme de AMOUNT"
.Function = xlSum
End With
ActiveSheet.PivotTables("Tableau croisé dynamique2").PivotFields( _
"CREATION_DATE").CurrentPage = "08/09/2016"
This code works to extract to filter with the date 08/09/2016.
Now, I would like to make the pivot table get this date in a cell ahead of launching the code.
But I don't want to have to go in to the code every time to change the date I want.
I would like something like this:
Ex: I write "09/09/2016" in cell "A1"
ActiveSheet.PivotTables("Tableau croisé dynamique2").PivotFields( _
"CREATION_DATE").CurrentPage = "A1"
But I am getting a debugging error.
After some testing, I found the cause (on my Excel Book). It was related to formatting the Pivot Field "CREATION_DATE", once I added the following section it worked.
Set PvtFld = PvtTbl.PivotFields("CREATION_DATE")
With PvtFld
.Orientation = xlPageField
.NumberFormat = "dd/mm/yyyy" ' << this line
.Position = 1
End With
And for the full code:
Sub PivotFilterDate()
Dim PvtTbl As PivotTable
Dim PvtFld As PivotField
' set your Pivot Table (after created) to a variable
Set PvtTbl = Sheets("PivotSpanish").PivotTables("Tableau croisé dynamique2")
' Set "CREATION_DATE" to a Pivot Field variable
Set PvtFld = PvtTbl.PivotFields("CREATION_DATE")
With PvtFld
.Orientation = xlPageField
.NumberFormat = "dd/mm/yyyy"
.Position = 1
End With
' you can modify your code to change all field setting, like following 2:
With PvtTbl.PivotFields("STATUS")
.Orientation = xlRowField
.Position = 1
End With
With PvtTbl.PivotFields("VENDOR_NAME")
.Orientation = xlRowField
.Position = 2
End With
' clear previous filters
PvtFld.ClearAllFilters
' --- trapping errors ---
' added a Boolean Flag to trap scenarios where no Pivot Item found that matches the value in Cell A1
Dim PvtItemExists As Boolean
PvtItemExists = False
' check all Pivot items in Pivot Field ("CREATION_DATE")
For Each PvtItem In PvtFld.PivotItems
' check if current Pivot Item equals the value in Cell A1
If PvtItem.Value = CStr(CDate(Range("D1").Value)) Then
PvtItemExists = True
Exit For
End If
Next PvtItem
If PvtItemExists Then
PvtFld.CurrentPage = CStr(CDate(Range("D1").Value))
Else
MsgBox "No data matches for date " & CDate(Range("D1").Value) & " in Pivot Table", vbCritical
End If
End Sub