.datapivotfield.orientation = xlhidden does not work - excel

I have a vba code which checks all the pivots in specified worksheets to add a range of pivotfield to the values/data section of the pivot because the pivot headers change every 4 weeks.
I have 6 pivots where this code works perfectly, but 2 pivots where I keep getting an error. I have tried to adjust the code but was not succesfull. I used this code to find the type for this pivot field as I thought it should be data, but it turns out to be 'hidden':
Set pvtTable = Worksheets("Sheet1").Range("A3").PivotTable
Set pvtField = pvtTable.PivotFields("ORDER_DATE")
Select Case pvtField.Orientation
Case xlHidden
MsgBox "Hidden field"
Case xlRowField
MsgBox "Row field"
Case xlColumnField
MsgBox "Column field"
Case xlPageField
MsgBox "Page field"
Case xlDataField
MsgBox "Data field"
End Select
I then checked this code on comparable fields in the pivots where it is working perfectly, expecting it would be data fields, but again it were hidden fields. I therefore do not understand what is different in these 2 pivots that makes my code not work compared to the pivots where the code works perfectly.
This is the code for the pivots where it is not working:
Sub AddAllFieldsValues_blad1()
Dim pt As PivotTable
Dim iCol As Long
Dim iColEnd As Long
Dim sheetnames As Variant
Dim I As Variant
With Sheets("blad1")
For Each pt In Sheets("blad1").PivotTables
With pt
.ManualUpdate = True
.DataPivotField.Orientation = xlHidden
iCol = 11
With .PivotFields(iCol)
If .Orientation = 0 Then
.Orientation = xlDataField
End If
End With
.ManualUpdate = False
pt.PivotCache.refresh
End With
Next pt
End With
End Sub
I only need the pivot to have 1 pivot field in the values section.
When I execute this code, I get this error:
error 1004:
propery orientation of class pivotfield cannot be set
And this line is marked when I click 'solve error' (or what it is called in english):
.DataPivotField.Orientation = xlHidden
I do not understand why because it works perfectly for the other pivots in the worksheet. The only thing that is different is that for those pivots, the code is slightly different:
Sub AddAllFieldsValues()
Dim pt As pivottable
Dim iCol As Long
Dim iColEnd As Long
Dim sheetnames As Variant
Dim I As Variant
sheetnames = Array("data pivots euros", "data pivots category - euros", "data pivots units", "data pivots category - units")
For I = LBound(sheetnames) To UBound(sheetnames)
With Sheets(sheetnames(I))
For Each pt In Sheets(sheetnames(I)).PivotTables
With pt
.ManualUpdate = True
.DataPivotField.Orientation = xlHidden
iCol = 12
iColEnd = .PivotFields.Count - 4
For iCol = 12 To iColEnd
With .PivotFields(iCol)
If .Orientation = 0 Then
.Orientation = xlDataField
End If
End With
Next iCol
.ManualUpdate = False
pt.PivotCache.refresh
End With
Next pt
End With
Next I
End Sub

The DataPivotField property is buggy, as it only works,
when your pivottable already has at least 2 datafields!
If you want to remove each datafield first, then replace the line
.DataPivotField.Orientation = xlHidden
by this:
Dim df as PivotField
For Each df In .DataFields
df.Orientation = xlHidden
Next df

Very late answer, but if anyone looks i believe this replicates what the question asks.
Dim xPivot As PivotTable
'setting exact pivot table also ensuring its targeting the correct sheet
Set xPivot = ThisWorkbook.Worksheets("Sheet1").PivotTables("Pivot_Table_Name")
'change "values" as required to view data fields/row fields etc
'change "Field Name" to match the value name
xPivot.PivotFields("Values").PivotItems("FieldName").Visible = False

Related

Pivot table to refresh active workbook, select Item "Period", clear all selection and choose 2 last values

After performing some operations this part of code goes to the sheet called "Overview", refreshes a huge pivot table - there is only one and it is called "PivotTable2" (actually, it doesn't refresh it and I don't know why). The part earlier that adds lines to the source works so after refreshing it manually everything works. Next, it chooses every cell with a value "Period" and what I need it to do is to clear filters in the selection "Period" and select two last values that pop up after the pivot table is refreshed.
ActiveWorkbook.Sheets("Overview").Activate
Dim pi As PivotItem
Dim pt As PivotTable
Dim pf As PivotField
For Each pt In ActiveSheet.PivotTables
pt.RefreshTable
Set pf = pt.PageFields("PivotTable2").PivotFields("Period")
For Each pf In pt.PageFields
pf.ClearManualFilter
pf.ClearAllFilters
pf.EnableMultiplePageItems = True
pf.AutoSort xlAscending, pf.SourceName
pf.CurrentPage = pf.PivotItems(pf.PivotItems.Count).Name
If pf.CurrentPage = "(blank)" And pf.PivotItems.Count > 2 Then
pf.CurrentPage = pf.PivotItems(pf.PivotItems.Count - 2).Name
End If
If pf.CurrentPage = "(blank)" And pf.PivotItems.Count > 1 Then
pf.CurrentPage = pf.PivotItems(pf.PivotItems.Count - 1).Name
End If
Next pf
Next pt
End Sub
Run-time error '1004':
Unable to get the PageFields property of the PivotTable class
I would be happy if you point at a problem or suggest a solution. Thank you!
This code works, but instead of only working with the field "Period" as my code suggests it performs operations on all fields in a pivot table and chooses 2 last values in a filter.
Dim pi As PivotItem
Dim pt As PivotTable
Dim pf As PivotField
For Each pt In ActiveSheet.PivotTables
pt.RefreshTable
Set pf = ActiveSheet.PivotTables("PivotTable2").PivotFields("Period")
For Each pf In pt.PageFields
pf.ClearManualFilter
pf.ClearAllFilters
pf.EnableMultiplePageItems = True
pf.AutoSort xlAscending, pf.SourceName
pf.CurrentPage = pf.PivotItems(pf.PivotItems.Count).Name
If pf.CurrentPage = "(blank)" And pf.PivotItems.Count > 2 Then
pf.CurrentPage = pf.PivotItems(pf.PivotItems.Count - 2).Name
End If
If pf.CurrentPage = "(blank)" And pf.PivotItems.Count > 1 Then
pf.CurrentPage = pf.PivotItems(pf.PivotItems.Count - 1).Name
End If
Next pf
Next pt

Pivot Table VBA code not displaying any result

I want to automate the pivot table process in my department for my colleagues that have trouble with Excel.
I found the code below online. It worked for me the last time, however, when I try to apply the same macro to another set of data (45000 rows vs. 4800 rows) it doesn't give me any result, just a blank page.
I read online that some versions of Excel cannot handle Data sets that have more than 65000 lines. I am currently using Excel 2016 at the office so I don't see what the problem is...
Can you please help me resolve the problem?
Dim PTableSA as PivotTable
Dim PCacheSA as PivotCache
Dim PRangeSA as Range
Dim PSheetSA as Worksheet
Dim DSheetSA as Worksheet
Dim LR_SA as Long
Dim LC_SA as Long
On Error Resume Next
Application.DisplayAlerts=False
Application.ScreenUpdating=False
Worksheets("TCD Sanctions").Delete
Worksheets.Add After:=ActiveSheet
ActiveSheet.Name = "TCD Sanctions"
Set PSheetSA = Worksheets("TCD Sanctions")
Set DSheetSA = Worksheets("Sanctions")
LR_SA = DSheet.Cells(Rows.Count, 1).End(xlUp).Row
LC_SA = DSheet.Cells(1, Columns.Count).End(xlToLeft).Column
Set PRangeSA = DSheetSA.Cells(1, 1).Resize(LR_SA, LC_SA)
Set PCacheSA = ActiveWorkbook.PivotCaches.Create(SourceType:=xlDatabase, SourceData:=PRangeSA).CreatePivotTable(TableDestination:=PSheetSA.Cells(2, 2),TableName:="TCD_Sanctions")
'I think the problem starts here when excel coumdn't create Pivot Table
Set PTableSA = PCacheSA.CreatePivotTable(TableDestination:=PSheetSA.Range("A1"),TableName:="TCD_Sanctions)
With ActiveSheet.PivotTables("TCD_Sanctions").PivotFields("Aggregate BU")
.Orientation = xlRowField
.Position = 1
End With
With ActiveSheet.PivotTables("TCD_Sanctions").PivotFields("Alert status")
.Orientation = xlRowField
.Position = 2
End With
With ActiveSheet.PivotTables("TCD_Sanctions").PivotFields("Year month")
.Orientation = xlColumnField
.Position = 1
End With
With ActiveSheet.PivotTables("TCD_Sanctions").PivotFields("Entity type")
.Orientation = xlPageField
.Position = 1
End With
'Defining pivot table format
Active.Sheet.PivotTables("TCD_Sanctions").ShowTableStyleRowStripes = True
Active.Sheet.PivotTables("TCD_Sanctions").TableStyle2 = "PivotStyleMedium9"
'Show in Tabular form
PSheet.PivotTables("TCD_Sanctions").RowAxisLayout xlTabularRow
Application.DisplayAlerts = True
Application.ScreenUpdating = True
ActiveSheet.PivotTables("TCD_Sanctions").AddDataField ActiveSheet.PivotTables( _
"TCD_Sanctions").PivotFields("Alert ID"), "Count of Alert ID", xlCount
End Sub

How to select the last item in a pivot filter for multiple pivot tables?

I need help with the below code and pivot table.
I run my script on a weekly basis and each time I need time select the last available item in the below pivot tables (PivotTable1, PivotTable2 and PivotTable3):
I tried the below code but it doesn't work:
Dim pi As PivotItem
Dim lLoop As Long
Dim pt As PivotTable
Dim lCount As Long
Dim lWeeks As Long
On Error Resume Next
lWeeks = 1
If lWeeks = 0 Then Exit Sub
Application.ScreenUpdating = False
Set pt = ActiveSheet.PivotTables("PivotTable1")
For Each pi In pt.PivotFields("Week").PivotItems
pi.Visible = False
Next pi
With pt.PivotFields("Week")
For lLoop = .PivotItems.Count To 1 Step -1
.PivotItems(lLoop).Visible = True
lCount = lCount + 1
If lCount = lWeeks Then Exit For
Next lLoop
End With
On Error GoTo 0
Application.ScreenUpdating = True
I also tried the below but it's still not working:
Sheets("Pivot").Select
ActiveSheet.PivotTables("PivotTable1").PivotCache.Refresh
ActiveSheet.PivotTables("PivotTable1").PivotFields("ExtractDate"). _
ClearAllFilters
ActiveSheet.PivotTables("PivotTable1").PivotFields("ExtractDate").CurrentPage _
= ThisWorkbook.Worksheets("Pivot").Range("B2").Value
In this case I'm having the Runtime Error 1004: Unable to get the PivotTables property of the Worksheet class.
Can you please advise how to modify the above codes to select the last available item in the 'Week' filter?
Also, how to modify this code to select the last value for these 3 pivot tables?
Thanks in advance.
You can set the current filter page with the name of the last (or first) PivotItem:
With ActiveSheet.PivotTables("PivotTable1").PageFields("Week")
.ClearManualFilter ' or ClearAllFilters
.AutoSort xlAscending, .SourceName
.CurrentPage = .Pivotitems(.Pivotitems.Count).Name
If .CurrentPage = "(blank)" And .Pivotitems.Count > 1 Then
.CurrentPage = .Pivotitems(.Pivotitems.Count - 1).Name
End If
End With
If the last entry is blank, it selects the previous one.
If you need the other end of your date range, just change xlAscending to xlDescending.
You can loop over all PivotTables in a worksheet and set each filter to the last page by this:
Dim pt As PivotTable
Dim pf As PivotField
Dim pi As PivotItem
For Each pt In ActiveSheet.PivotTables
pt.RefreshTable
' Set pf = pt.PageFields("Week")
For Each pf In pt.PageFields
pf.ClearManualFilter ' or ClearAllFilters
pf.EnableMultiplePageItems = True
pf.AutoSort xlAscending, pf.SourceName
pf.CurrentPage = pf.Pivotitems(pf.Pivotitems.Count).Name
If pf.CurrentPage = "(blank)" And pf.Pivotitems.Count > 1 Then
pf.CurrentPage = pf.Pivotitems(pf.Pivotitems.Count - 1).Name
End If
Next pf
Next pt
At least 1 item has to remain visible, so you can't loop over all items and set them .Visible = False. A loop over all except the last PivotItem should work, but is too slow.
I added a .RefreshTable to refresh the data in your PivotTable. If there are still wrong informations, you can refresh the PivotCache of your workbook additionally:
Dim pc As PivotCache
For Each pc In ActiveWorkbook.PivotCaches
pc.MissingItemsLimit = xlMissingItemsNone
pc.Refresh
Next pc

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:

PivotFields property of the PivotTable Class problems

I know I will be marked down for this but here it goes.
I have been going through several forums and informative websites regarding this error but I just cant work out what is wrong.
The error is:
Run-time error '1004': Unable to get the PivotFields property of the PivotTable Class
This occurs at the line:
With Sheets("PivotTable1").PivotTables("Occupancy").PivotFields("Precinct")
I have seen reference that the error may be because the field is not called "Precinct". However I have copy and pasted it directly and have also ensured that the code "writes" that particular heading. I just can't figure it out. Could it be something to do with refreshing the data or pivot table? Is there a way to replace "Precinct" in the problem line with a cell reference?
The code is:
Sub OccupancyPivot()
Dim SrcData As Variant
Dim LRow As Long, LCol As Long
Dim wsSheet As Worksheet
Dim PTCache As PivotCache
Dim PT As PivotTable
'Determine the data range you want to pivot
LRow = Cells(Rows.Count, 1).End(xlUp).Row
LCol = Cells(1, Columns.Count).End(xlToLeft).Column
Set SrcData = Worksheets("Raw Data").Range("A1:" & Cells(LRow, LCol).Address(False, False))
Sheets.Add.Name = "PivotTable1"
Set PTCache = ActiveWorkbook.PivotCaches.Add(xlDatabase, SrcData)
Set PT = PTCache.CreatePivotTable(Sheets("PivotTable1").Range("A1"), "Occupancy")
'Create the headings and row and column orientation
With Sheets("PivotTable1").PivotTables("Occupancy").PivotFields("Precinct")
.Orientation = xlRowField
.Position = 1
End With
With Sheets("PivotTable1").PivotTables("Occupancy").PivotFields("Registration")
.Orientation = xlDataField
.Function = xlCount
End With
With Sheets("PivotTable1").PivotTables("Occupancy").PivotFields("Captured Date")
.Orientation = xlColumnField
.Position = 1
End With
With Sheets("PivotTable1").PivotTables("Occupancy").PivotFields("Captured Session")
.Orientation = xlColumnField
.Position = 2
End With
With Sheets("PivotTable1").PivotTables("Occupancy").PivotFields("Location")
.Orientation = xlRowField
.Position = 2
End With
'ActiveWorkbook.Sheets("PivotTable").Visible = xlSheetVeryHidden
End Sub
Anyone able to tell me what is wrong with the above?
Edit: I have found a couple of other mentions of this occurring. For some reason when a pivot sub procedure is part of other sub procedures, the pivotfields don't recognize the headings in the data. I am yet to find a definitive reason for this but believe it has something to do with refreshing the pivot and data.
Try the modified code below, I added also cases where you already created the "PivotTable1" sheet and "Occupancy" Pivot table (in previous runs of this code), and then you just want to refresh the Pivot's data with the modified data in "Raw Data" sheet.
Sub OccupancyPivot()
Dim SrcData As Variant
Dim LRow As Long, LCol As Long
Dim wsSheet As Worksheet
Dim PTCache As PivotCache
Dim PT As PivotTable
Dim PivotShtExists As Boolean
' Determine the data range you want to pivot
LRow = Worksheets("Raw Data").Cells(Worksheets("Raw Data").Rows.Count, 1).End(xlUp).Row
LCol = Worksheets("Raw Data").Cells(1, Worksheets("Raw Data").Columns.Count).End(xlToLeft).Column
Set SrcData = Worksheets("Raw Data").Range("A1:" & Cells(LRow, LCol).Address(False, False))
' check is "PivotTable1" sheet already exists (from previous Macro runs)
For Each wsSheet In ThisWorkbook.Sheets
If wsSheet.Name = "PivotTable1" Then
PivotShtExists = True
End If
Next wsSheet
If Not PivotShtExists Then Sheets.Add.Name = "PivotTable1"
Set wsSheet = ThisWorkbook.Sheets("PivotTable1")
Set PTCache = ActiveWorkbook.PivotCaches.Add(xlDatabase, SrcData)
' add this line in case the Pivot table doesn't exit >> first time running this Macro
On Error Resume Next
Set PT = wsSheet.PivotTables("Occupancy") ' check if "Occupancy" Pivot Table already created (in past runs of this Macro)
On Error GoTo 0
If PT Is Nothing Then
' create a new Pivot Table in "PivotTable1" sheet, start from Cell A1
Set PT = wsSheet.PivotTables.Add(PivotCache:=PTCache, TableDestination:=wsSheet.Range("A1"), TableName:="Occupancy")
'Create the headings and row and column orientation
With PT.PivotFields("Precinct")
.Orientation = xlRowField
.Position = 1
End With
With PT.PivotFields("Registration")
.Orientation = xlDataField
.Function = xlCount
End With
With PT.PivotFields("Captured Date")
.Orientation = xlColumnField
.Position = 1
End With
With PT.PivotFields("Captured Session")
.Orientation = xlColumnField
.Position = 2
End With
With PT.PivotFields("Location")
.Orientation = xlRowField
.Position = 2
End With
Else
' just refresh the Pivot cache with the updated Range (data in Sheet1)
PT.ChangePivotCache PTCache
PT.RefreshTable
End If
'ActiveWorkbook.Sheets("PivotTable").Visible = xlSheetVeryHidden
End Sub
After running this code, multiple scanarios, this is the result I am getting (simulated data):
Based on what you've said so far, I think your LRow and/or Lcol variables are being set from the wrong sheet, so your source data isn't what it should be. Try this:
Sub OccupancyPivot()
Dim SrcData As String
Dim wsSheet As Worksheet
Dim PTCache As PivotCache
Dim PT As PivotTable
'Determine the data range you want to pivot
SrcData = "'Raw Data'!" & Worksheets("Raw Data").Range("A1").CurrentRegion.Address(ReferenceStyle:=xlR1C1)
Sheets.Add.Name = "PivotTable1"
Set PTCache = ActiveWorkbook.PivotCaches.Add(xlDatabase, SrcData)
Set PT = PTCache.CreatePivotTable(Sheets("PivotTable1").Range("A1"), "Occupancy")
'Create the headings and row and column orientation
With PT
With .PivotFields("Precinct")
.Orientation = xlRowField
.Position = 1
End With
With .PivotFields("Registration")
.Orientation = xlDataField
.Function = xlCount
End With
With .PivotFields("Captured Date")
.Orientation = xlColumnField
.Position = 1
End With
With .PivotFields("Captured Session")
.Orientation = xlColumnField
.Position = 2
End With
With .PivotFields("Location")
.Orientation = xlRowField
.Position = 2
End With
End With
'ActiveWorkbook.Sheets("PivotTable").Visible = xlSheetVeryHidden
End Sub

Resources