VBA PivotItems Index Variable - vba

I am trying to loop through different years of data from a OLAP pivot table and for each year I have to drilldown to get the data I am looking for. Here is what the macro recorder gave me for 2013:
'This is the cell that has to be drilled down
Range("A2").Select
With ActiveSheet.PivotTables("PivotTable1").PivotFields("[Date].[YMD].[Year Name]") _
.PivotItems("[Date].[YMD].[Year Name].&[***2013***]").DrilledDown = True
End With
[Date].[YMD] is the field name and [Year Name] is the source name.
However I am trying to replace the &[2013] with a variable "Yr" which will allow me to select and then drill down into each year.
But I get the following message: "Unable to get the PivotItems property of the PivotField class"
Is there a specific syntax for PivotItems Index? Are there limitations to using a variable to reference from an OLAP Pivot Table? I have tried defining Yr as a Double and also as a Variable but it didn't help..
Thanks for any advice!!

Try this
Dim YR As Integer
YR = 2013
With ActiveSheet.PivotTables("PivotTable1").PivotFields("[Date].[YMD].[Year Name]") _
.PivotItems("[Date].[YMD].[Year Name].&[" & YR & "]").DrilledDown = True
End With

Related

Excel VBA to filter Pivot Table and Pivot Chart for previous day - Pivot Filter Field

Here is my problem, every bit of code, every alteration, every type, doesn't work. I'm using Office 360 at my work site (up to date), so it's excel 2016 and VBA 7.1.
What I'm looking to do is automate our end of shift reports. Here's the process:
We enter data into an excel sheet (Log) every hour. At the end of the day, at 5:00 AM, we save and close that log, open another excel sheet that IMPORTS the data into power pivot, and displays it on a PivotTable (formatting for printing for our bosses), and we choose the filter for the previous date using the filter drop down, and print it. We do this with three (3) reports: 2 PivotTables, and 1 PivotChart. Power Pivot imports ALL of the data from the Log sheet to reformat it for printing.
I've successfully managed to get and rewrite the code (beginner at this) for the automation process of: auto saving the log, closing the log, opening the Report workbook, refreshing the data, and printing the data, then closing the report. The only part I'm now missing is the auto-filtering.
The code I've tried is vast, but here's an example of what I've tried recently (I've erased and re-copied so many codes...)
Sub Filter_PivotField()
'Description: Filter a pivot table or slicer for a specific date or period
'Source: excelcampus.com/vba/filter-pivot-table-slicer-recent-date-period
Dim sSheetName As String
Dim sPivotName As String
Dim sFieldName As String
Dim sFilterCrit As String
Dim pi As PivotFields
'Set the variables
sSheetName = "EOS Report"
sPivotName = "PivotTable1"
sFieldName = "Date"
sFilterCrit = "xlDateYesterday"
'sFilterCrit = ThisWorkbook.Worksheets("EOS Report").Range("O1").Value
With ThisWorkbook.Worksheets(sSheetName).PivotTables(sPivotName).PivotFields(sFieldName)
'Clear all filter of the pivotfield
.ClearAllFilters
'Loop through pivot items of the pivot field
'Hide or filter out items that do not match the criteria
For Each pi In .PivotFields
If pi.Name <> sFilterCrit Then
pi.Visible = False
End If
Next pi
End With
End Sub
To no avail....
When I record a macro doing the manual filter, I get this:
Sub manualfilter()
'
' manualfilter Macro
'
'
ActiveSheet.PivotTables("PivotTable1").PivotFields( _
"[Bi-Hourly Report].[Date].[Date]").VisibleItemsList = Array( _
"[Bi-Hourly Report].[Date].&[2016-09-28T00:00:00]")
End Sub
But it fails when I try to re-run the same macro that I just recorded (after changing the date back). I've enabled and disabled multiple selection option, etc.
Not to mention, trying to auto-filter a chart is a nightmare because tables, yea there's tons of articles on it, but charts? not much comes up on researching.
Here's images of the filter button, because almost everything I've researched is to sort the COLUMN of the Table, not the filter itself with a PivotTable.
Table Filter
Chart Filter
I cannot post the actual excel spreadsheets as they are proprietary property of the company, but I can replicate the format with false data if needed.
check this out.
Dim prev_date As String
prev_date = Month(Date - 1) & "/" & Day(Date - 1) & "/" & Year(Date - 1)
Thisworkbook.Sheets("Sheet1").Activate
'change this line with your sheet where pivot table is present. Change Sheet name.
ActiveSheet.PivotTables("PivotTable1").RefreshTable
ActiveSheet.PivotTables("PivotTable1").PivotFields("Date").CurrentPage = prev_date

Use VBA to capture the fields in pivot table

We can use below code to build a Pivot Table (This is a pivot table created by Power Pivot).
With ActiveSheet.PivotTables("PivotTable1").CubeFields(FieldName)
.Orientation = Orientation
.Position = Position
Is there some way to reverse the process? Suppose user has built a pivot table. We use VBA to capture the fields used on the table (find out corresponding FieldName(s), Orientation(s), and Position(s)) and save them, so next time, user can just run the macro and create the same pivot table again.
Thanks
Thanks to #OpiesDad. Below will work.
Sub Func1()
Dim objCubeFld As PivotField
Dim pvt As PivotTable
Set pvt = ActiveSheet.PivotTables("PivotTable1")
For Each objCubeFld In pvt.PivotFields
MsgBox objCubeFld & "-" & objCubeFld.Orientation
Next objCubeFld
End Sub

excel real time refresh of filter

In my Pivot Table in excel, I have a field List about the due date of some reports.
For example, 10/5/2016
My problem is, every day I have to choose the date so that I can see the report code, I don't want it to be this. What I want is, everyday I open the excel, the filter will automatically change from 10/5/2016 to 11/5/2016.
What function / VBA should I use?
Helps
If you want a VBA solution, add the following to the ThisWorkbook code.
Private Sub Workbook_Open()
Dim tDay As Date, pf As PivotField
tDay = Date
Set pf = Sheets("name of worksheet").PivotTables("pivot table name").PivotFields("insert the name of your filter here")
pf.ClearAllFilters
pf.CurrentPage = tDay
End Sub
Change the sheet name, pivot table name and the name of the filter.
If you need to do more VBA manipulation of pivot tables I suggest reading the following http://www.thespreadsheetguru.com/blog/2014/9/27/vba-guide-excel-pivot-tables.

Excel VBA: PivotTable CubeField Fact Table Name?

I'm working with a large OLAP Cube, and I'm building very rudimentary search functionality to help me parse through the amount of data (~30 fact tables, 30 dimensions, plus calculated measures), but I've come across an interesting issue. When I access a CubeField.Name property for a fact table member or a calculated measure, it comes through as [Measures].[FieldName] instead of pointing me to the correct Fact table / calculated measure folder.
Here's the code I'm using:
Sub X()
Dim pvtTable As PivotTable
Dim oCubeField As CubeField
Set pvtTable = ActiveSheet.PivotTables(1)
For Each oCubeField In pvtTable.CubeFields
If InStr(LCase(oCubeField.Name), "spread") > 0 Then
Debug.Print oCubeField.Parent & ": " & oCubeField.Name
End If
Next
End Sub
Any ideas on how I can actually reach the fact table name? Or the calculated measure's folder structure? Thanks!
Try oCubeField.Value perhaps. The reference for the CubeField object says:
Name Returns a String value that represents the name of the object.
Value Returns a String value that represents the name of the specified field.
Unfortunately, you can't do that, because a measure expression may link to a few fact tables.
But you can query and analyse cube metadata with OpenSchema() function.
Something like this:
Sub GetMeasuresList()
Const adSchemaMeasures = 36
Set ADOCon = ActiveCell.PivotTable.PivotCache.ADOConnection
Set RecSet = ADOCon.OpenSchema(adSchemaMeasures)
While Not RecSet.EOF
Debug.Print RecSet!MEASURE_NAME & ": " & RecSet!EXPRESSION
RecSet.MoveNext
Wend
End Sub
OLE DB for OLAP Schema Rowsets
How To Use the ADO OpenSchema Method in Visual Basic

Excel VBA: Output Distinct Values and Subtotals

I have data of this form:
Category Source Amount
Dues FTW $100
Donations ODP $20
Donations IOI $33
Dues MMK $124
There is no sort order. The categories are unknown at compile time. I want a VBA macro to cycle through the range, output a list of distinct values, with the subtotals for each. For the above data, it would look like this:
Category Total Amount
Dues $224
Donations $55
How can I do this? Also, is there a way to make the macro run every time the table above is updated, or is it necessary for the user to click a button?
You may want to use a built in Excel feature to do this. Looping can take a long time and be problematic if you have a lot of values to loop through.
Something like the following might get you started on creating a pivot table (from http://www.ozgrid.com/News/pivot-tables.htm)
Sub MakeTable()
Dim Pt As PivotTable
Dim strField As String
'Pass heading to a String variable
strField = Selection.Cells(1, 1).Text
'Name the list range
Range(Selection, Selection.End(xlDown)).Name = "Items"
'Create the Pivot Table based off our named list range.
'TableDestination:="" will force it onto a new sheet
ActiveWorkbook.PivotCaches.Add(SourceType:=xlDatabase, _
SourceData:="=Items").CreatePivotTable TableDestination:="", _
TableName:="ItemList"
'Set a Pivot Table variable to our new Pivot Table
Set Pt = ActiveSheet.PivotTables("ItemList")
'Place the Pivot Table to Start from A3 on the new sheet
ActiveSheet.PivotTableWizard TableDestination:=Cells(3, 1)
'Move the list heading to the Row Field
Pt.AddFields RowFields:=strField
'Move the list heading to the Data Field
Pt.PivotFields(strField).Orientation = xlDataField
End Sub
This is for subtotals (though I much prefer pivot tables)
http://msdn.microsoft.com/en-us/library/aa213577(office.11).aspx
EDIT:
I reread and have the following thoughts. Set up the pivot table on a separate sheet (without using any code) then put the following code on the sheet that has the pivot table so that the table will update everytime the sheet is selected.
Private Sub Worksheet_Activate()
Dim pt As PivotTable
'change "MiPivot" to the name of your pivot table
Set pt = ActiveSheet.PivotTables("MyPivot")
pt.RefreshTable
End Sub
Edit #2
Refresh all pivot tables on sheet
http://www.ozgrid.com/VBA/pivot-table-refresh.htm
Private Sub Worksheet_Activate()
Dim pt As PivotTable
For Each pt In ActiveSheet.PivotTables
pt.RefreshTable
Next pt
End Sub
The link has multiple options on how to refresh pivot tables in the sheet/workbook.