pivot chart "For Each" function - vba

I am trying to make a pivot chart change its axis subject based on a dropdown value in a cell. I have been able to get this work when changing the data fields (values) using the following code.
Dim PT As PivotTable
Dim PF As PivotField
Dim sField As String
For Each PF In PT.DataFields
If PF.Name <> sField Then
PF.Orientation = xlHidden
End If
Next PF
However, when I try to do the same for the axis of the pivot chart I get a run time error (424 - object required) using the following code. I believe that the issue lies in the "PivotTable.PivotAxis" line and has something to do with the .PivotAxis.
Dim PT As PivotTable
Dim PF As PivotField
Dim sField As String
Dim PA As PivotAxis
For Each PA In PT.PivotAxis
If PA.Name <> sField Then
PA.Orientation = xlHidden
End If
Next PA
Does anyone have any solutions as to how I can check each pivot axis name in a pivot chart iteratively?

Related

Naming a chart created with .shapes.chart

I've been trying to figure out what i'm doing wrong but I can't find the answer. I've got the following code:
Sub CreatePivotChart()
Dim sh As Shape
Dim ws As Worksheet
Dim ch As Chart
Dim pt As PivotTable
DeleteAllChartObjects
'setting ws and sh will be done alot here. It's basically making it easy for yourself by making a new (short name):
Set ws = Worksheets("Analysis")
Set sh = ws.Shapes.AddChart(XlChartType:=xlColumn, Width:=400, Height:=200)
'This part to make sure that when there's no cell selected when running the code) within the pivottable, it still works
Set ch = sh.Chart
'Acipivot is created as title for the pivottable in sbCreativpivot:
Set pt = Worksheets("PivotTable").PivotTables("Acpivot")
ch.SetSourceData pt.TableRange1
'align the chart with the table:
sh.Top = pt.TableRange1.Top
sh.Left = pt.TableRange1.Left + pt.TableRange1.Width + 10
End Sub
Everything works fine, except I can't name the chart. I've tried several methods that I found online, but none of them seem to work.
Here's my latest attempt:
'This part to make sure that when there's no cell selected when running the code) within the pivottable, it still works
Set ch = sh.Chart
With ch
With .Parent.Name = "test"
End With
End With
But if I then try to reference it like here:
Sub EditPivotChart()
Dim pt As PivotTable
Dim ch As Chart
Dim pf As PivotField
Set ch = Charts("test")
Set pt = ch.PivotLayout.PivotTable
For Each pf In pt.VisibleFields
pf.Orientation = xlHidden
Next pf
End Sub
I get an error
vba ran out of memory
Does anyone see what wrong I am doing?
Thanks!
You can remove all of the following segment
With ch
With .Parent.Name = "test"
End With
End With
and simply replace it with
sh.Name = "test"
That should do the trick.

Code to cycle through and save pivot table fields stopped working...any ideas?

I am trying to cycle through items in pivot table field and save the pdf of the page for each. I had this set up and working but a was tweaking it and now it is throwing an error when it hits pf.CurrentPAge = pi.Value. I'm pulling my hair out as I can't figure out what changed to suddenly make it stop working (in the course of an hour!). Any one have any ideas?
Sub Test()
Dim pt As PivotTable, pi As PivotItem, pf As PivotField
Dim lLoop As Long
Dim strExportPath As String
Set pt = ActiveSheet.PivotTables(1)
Set pf = pt.PivotFields("AU & Name")
strExportPath = "C:\Users\nbelair\desktop"
For Each pi In pf.PivotItems
pf.CurrentPage = pi.Value
ActiveSheet.ExportAsFixedFormat Type:=xlTypePDF, Filename:=strExportPath
& "\" & "test.pdf"
Next pi
End Sub

Pass A Variable Pivot Filed Name To Sort VBA

I'm working with a pivot table, and am using the following code:
Sub SortCTRDescending()
ActiveSheet.PivotTables("PivotTable6").PivotFields("Industry").AutoSort _
xlDescending, "Total CTR", ActiveSheet.PivotTables("PivotTable6"). _
PivotColumnAxis.PivotLines(6), 1
End Sub
Is there a way to pass the Pivot Field "Industry" as a variable depending on what is selected in the pivot table rows? i.e. if Industry changes to "List Name", have the variable set to whatever row label selected (assumes only 1 row label)? These then get passed to a button, which would "sort by CTR" or "sort by Open Rate" where column numbers stay the same.
Edit: Added a screenshot of the data. The Row Label is Industry, but this can change to any of the other fields, how can I make the first row label the primary sorting variable.
You can loop through the RowFields of the PivotTable to find the name of the current field. The code checks to ensure that the table currently has only 1 RowField. Make adjustments for your specific object names.
Sub SortCTRDescending()
Dim ws As Worksheet
Dim pt As PivotTable
Dim pf As PivotField, pField As PivotField
Dim sField As String
Set ws = Worksheets("Sheet1") 'change as needed
Set pt = ws.PivotTables("PivotTable6")
If pt.RowFields.Count = 1 Then
'note that even though there is only one field, the loop is needed to get the name
For Each pField In pt.RowFields
sField = pField.Name
Next
Else
MsgBox "Whoa! More Than 1 Row Field!"
Exit Sub
End If
Set pf = pt.PivotFields(sField)
pf.AutoSort xlDescending, "Total CTR", pt.PivotColumnAxis.PivotLines(6), 1
End Sub

Select/Deselect all Pivot Items

I have a pivot table, and I am trying to select certain pivot items based on values in an array. I need this process to go faster, so I have tried using Application.Calculation = xlCalculationManual and PivotTables.ManualUpdate = True, but neither seem to be working; the pivot table still recalculates each time I change a pivot item.
Is there something I can do differently to prevent Excel from recalculating each time?
Or is there a way to deselect all items at once (not individually) to make the process go quicker?
Here is my code:
Application.Calculation = xlCalculationManual
'code to fill array with list of companies goes here
Dim PT As Excel.PivotTable
Set PT = Sheets("LE Pivot Table").PivotTables("PivotTable1")
Sheets("LE Pivot Table").PivotTables("PivotTable1").ManualUpdate = True
Dim pivItem As PivotItem
'compare pivot items to array.
'If pivot item matches an element of the array, make it visible=true,
'otherwise, make it visible=false
For Each pivItem In PT.PivotFields("company").PivotItems
pivItem.Visible = False 'initially make item unchecked
For Each company In ArrayOfCompanies()
If pivItem.Value = company Then
pivItem.Visible = True
End If
Next company
Next pivItem
It seems that you really want to try something different to significantly reduce the time it takes to select the required items in pivotttable.
I propose to use a “MirrorField”, i.e. a copy of the “Company” to be used to set in the sourcedata of the pivottable the items you need to hide\show.
First you need to add manually (or programmatically) the “MirrorField” and named same as the source field with a special character at the beginning like “!Company” the item must be part of the sourcedata and it can be placed in any column of it (as this will a “programmer” field I would place it in the last column and probably hidden as to not creating any issues for\with the users)
Please find below the code to update the pivottable datasource and to refresh the pivottable
I’m also requesting the PivotField to be updated just make it flexible as it then can be used for any field (provided that the “FieldMirror” is already created)
Last: In case you are running any events in the pivottable worksheet they should be disable and enable only to run with the last pivottable update
Hope this is what you are looking for.
Sub Ptb_ShowPivotItems_MirrorField(vPtbFld As Variant, aPtbItmSelection As Variant)
Dim oPtb As PivotTable
Dim rPtbSrc As Range
Dim iCol(2) As Integer
Dim sRC(2) As String
Dim sFmlR1C1 As String
Dim sPtbSrcDta As String
Rem Set PivotTable & SourceData
Set oPtb = ActiveSheet.PivotTables(1)
sPtbSrcDta = Chr(34) & oPtb.SourceData & Chr(34)
Set rPtbSrc = Evaluate("=INDIRECT(" & sPtbSrcDta & ",0)")
Rem Get FieldMirrow Position in Pivottable SourceData (FieldMirrow Already present SourceData)
With rPtbSrc
iCol(1) = -1 + .Column + Application.Match(vPtbFld, .Rows(1), 0)
iCol(2) = Application.Match("!" & vPtbFld, .Rows(1), 0)
End With
Rem Set FieldMirror Items PivotTable SourceData as per User Selection
sRC(1) = """|""&RC" & iCol(1) & "&""|"""
sRC(2) = """|" & Join(aPtbItmSelection, "|") & "|"""
sFmlR1C1 = "=IF(ISERROR(SEARCH(" & sRC(1) & "," & sRC(2) & ")),""N/A"",""Show"")"
With rPtbSrc.Offset(1).Resize(-1 + rPtbSrc.Rows.Count).Columns(iCol(2))
.Value = "N/A"
.FormulaR1C1 = sFmlR1C1
.Value = .Value2
End With
Rem Refresh PivotTable & Select FieldMirror Items
With oPtb
Rem Optional: Disable Events - In case you are running any events in the pivottable worksheet
Application.EnableEvents = False
.ClearAllFilters
.PivotCache.Refresh
With .PivotFields("!" & vPtbFld)
.Orientation = xlPageField
.EnableMultiplePageItems = False
Rem Optional: Enable Events - To triggrer the pivottable worksheet events only with last update
Application.EnableEvents = True
.CurrentPage = "Show"
End With: End With
End Sub
It seems unavoidable to have the pivotable refreshed every time a pivotitem is updated.
However I tried approaching the problem from the opposite angle. i.e.:
1.Validating the “PivotItems to be hidden” before updating the pivottable.
2.Also making make all items visible at once instead of “initially make item unchecked” one by one.
3.Then hiding all the items not selected by the user (PivotItems to be hidden)
I ran a test with 6 companies selected out of a total of 11 and the pivottable was updated 7 times
Ran also your original code with the same situation and the pivottable was updated 16 times
Find below the code
Sub Ptb_ShowPivotItems(aPtbItmSelection As Variant)
Dim oPtb As PivotTable
Dim oPtbItm As PivotItem
Dim aPtbItms() As PivotItem
Dim vPtbItm As Variant
Dim bPtbItm As Boolean
Dim bCnt As Byte
Set oPtb = ActiveSheet.PivotTables(1)
bCnt = 0
With oPtb.PivotFields("Company")
ReDim Preserve aPtbItms(.PivotItems.Count)
For Each oPtbItm In .PivotItems
bPtbItm = False
For Each vPtbItm In aPtbItmSelection
If oPtbItm.Name = vPtbItm Then
bPtbItm = True
Exit For
End If: Next
If Not (bPtbItm) Then
bCnt = 1 + bCnt
Set aPtbItms(bCnt) = oPtbItm
End If
Next
ReDim Preserve aPtbItms(bCnt)
.ClearAllFilters
For Each vPtbItm In aPtbItms
vPtbItm.Visible = False
Next
End With
End Sub

Excel VBA - PivotTable Filter Runtime Error '1004' PivotItems

I have the following code, which opens an excel file, selects the sheet and runs a macro - I have then managed to make it remove the filter for Date, but I am then having trouble getting it to filter to "01/07/2013"
Sub Data()
Dim oExcel As Excel.Application
Dim oWB As Workbook
Dim oSheets As Sheets
Dim oPi As PivotItem
Set oExcel = New Excel.Application
oExcel.Workbooks.Open ("\\A79APBRSFACTD\MDSS\FactivityServer\FactShar\OEE_Daily2.xls")
oExcel.Visible = True
Set oExcel = Excel.Application
Set oWB = oExcel.Workbooks("OEE_Daily2.xls")
oWB.Sheets("OEE Pivot Daily").Select
oExcel.Run ("Update_OEE_Daily")
oWB.Sheets("OEE Pivot Daily").Range("B3").Select
With oWB.Sheets("OEE Pivot Daily").PivotTables("PivotTable2").PivotFields("Date")
.ClearAllFilters
.PivotItems("01/07/2013").Visible = True
End With
Set oExcel = Nothing
Set oWB = Nothing
End Sub
I receive the following error message Run-time error '1004': Unable to get the PivotItems property of the PivotField class
The date "01/07/2013" is available in the source data of the PivotTable, and I am able to select it manually, but not automatically.
This is baffling me, as I only need it to show the one date.
If you're trying to show only 01/07/2013, then once you've cleared the filter, you need to hide everything except 01/07/2013, so try this:
With oWB.Sheets("OEE Pivot Daily").PivotTables("PivotTable2").PivotFields("Date")
.ClearAllFilters
For Each oPi In .PivotItems
If oPi .Value <> "1/7/2013" Then
oPi .Visible = False
End If
Next pi
End With
Make sure you remove the zeros.
If you step through your code, and watch oPi.value, you will see that it is "1/7/2013" instead of "01/07/2013". At least it was for me.
Excel is a nightmare when it comes to regional dates, so if you are using US mm/dd/yyyy format, this should work. If you're using dd/mm/yyyy format, you will need to check oPi.value against an American-formatted date. Annoyingly.
Edited 23/07/2013:
New code to search the data before applying the filter and lots of re-formatting to get around the American date format issue:
Sub RunFilter()
Dim strFilterDate As String
Dim datFilterDate As Date
Dim rngDateRange As Range
Dim c As Range
strFilterDate = InputBox("Enter the filter date in dd/mm/yyyy format.", "Enter date", Format(Now(), "dd/mm/yyyy"))
If IsDate(strFilterDate) And Len(strFilterDate) = 10 Then
datFilterDate = DateSerial(Right(strFilterDate, 4), Mid(strFilterDate, 4, 2), Left(strFilterDate, 2))
Set rngDateRange = ThisWorkbook.Worksheets("Sheet1").Range("B:B").SpecialCells(xlCellTypeConstants)
For Each c In rngDateRange
If c.Value2 = datFilterDate Then
ApplyPTFilter (datFilterDate)
Exit For
End If
Next c
End If
End Sub
Sub ApplyPTFilter(datDate As Date)
Dim pi As PivotItem
Dim strDate As String
strDate = Format(datDate, "m/d/yyyy")
With ThisWorkbook.Sheets("OEE Pivot Daily").PivotTables("PivotTable2").PivotFields("Date")
.ClearAllFilters
For Each pi In .PivotItems
If pi.Value <> strDate Then
pi.Visible = False
End If
Next pi
End With
End Sub
I realize that I bumped on similar issue waaay after the original post, although this thread was very inspiring - what helped me was:
.PivotCache.MissingItemsLimit = xlMissingItemsNone
After clearing the retained items from the pivotfilter list - I managed to execute my code without fail, what went after this was:
FiltrArr = Array("wymagalne", "wymagalne na jutro", "przeterminowane", "puste")
For Each PivotItem In .PivotFields("status").PivotItems
If Not IsError(Application.Match(PivotItem.Caption, FiltrArr, 0)) Then
PivotItem.Visible = True
Else
PivotItem.Visible = False
End If
Next PivotItem