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

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

Related

.datapivotfield.orientation = xlhidden does not work

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

How select multiple Pivot Items using formula in VBA from a Pivot Field

I'm trying use VBA to select all organizations that have a H or N as their fourth character.
I've tried modifying code to select either just H or N and it works. Also this code works, if I reverse the signs by selecting everything that's not H or N.
Sub Select_H_and_N_Organizations_View()
Dim WS As Worksheet
Dim PT As PivotTable
Dim PF As PivotField
Dim PI As PivotItem
Dim blnCheck As Boolean
blnCheck = False
Set WS = ActiveWorkbook.ActiveSheet
If WS.PivotTables.Count > 0 Then
Set PT = WS.PivotTables(1)
PT.ManualUpdate = True
Set PF = PT.PivotFields("Organization")
For Each PI In PF.PivotItems
If Mid(PI.Name, 4, 1) = "H" Or Mid(PI.Name, 4, 1) = "N" Then
blnCheck = True
End If
Next PI
If blnCheck = True Then
Set PF = PT.PivotFields("Organization")
For Each PI In PF.PivotItems
If Mid(PI.Name, 4, 1) = "H" Or Mid(PI.Name, 4, 1) = "N" Then
If PI.Visible = False Then
PI.Visible = True
End If
End If
Next PI
For Each PI In PF.PivotItems
If Mid(PI.Name, 4, 1) <> "H" Or Mid(PI.Name, 4, 1) <> "N" Then
If PI.Visible = True Then
PI.Visible = False ''This is where code breaks
End If
End If
Next PI
Else
MsgBox "There are no H or N Organizations available.", vbOKOnly, "Pivot Tables"
End If
End If
PT.ManualUpdate = False
Set WS = Nothing
Set PT = Nothing
Set PF = Nothing
Set PI = Nothing
End Sub
You checked first, if there is any pivotitem fulfilling your criteria. That is correct, as at least one pivotitem must remain visible.
Then you switched each wanted pivotitem visible.
At last, you want to hide all unwanted. There you just have to change your condition from Or to And, as otherwise your condition is always met (all would be invisible, and the error occurs at the last pivotitem, as one must remain visible):
If Mid(PI.Name, 4, 1) <> "H" And Mid(PI.Name, 4, 1) <> "N" Then

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:

VBA-PIVOT TABLE WIZARD METHOD

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

Resources