Trying to pull DataField from PivotTable using VBA in Excel - excel

I am trying to pull both a column value and a data value out of a pivot table, using Excel.
For j = 1 To 1 'pt.RowFields(i).PivotItems.Count
sum = pt.DataFields(2).PivotItems(j)
Client = pt.RowFields(1).PivotItems(j)
Sheets("InvoiceTemplate").Range("c7").Value = Client
Sheets("InvoiceTemplate").Range("i13").Value = sum
Next
The Client value comes back exactly as expected. However, the sum value throws the error:
Unable To Get PivotItems Property from PivotField class.
With a PivotTable that looks like the below, I would expect results of Contoso and £60.50
net gross
Contoso £50.00 £60.50
Adventureworks £100 £110.00
Any idea as to what I am doing wrong? By the way, I know I have a 1 TO 1 loop, but this will be modified once this is working.

I think this does what you want:
Sub PrintPivotFields()
Dim pvt As Excel.PivotTable
Dim pvtAcctField As Excel.PivotField
Dim pvtNetField As Excel.PivotField
Dim pvtItem As Excel.PivotItem
Set pvt = ActiveCell.PivotTable
Set pvtAcctField = pvt.RowFields(1)
Set pvtNetField = pvt.DataFields(1)
For Each pvtItem In pvtAcctField.PivotItems
Debug.Print pvtItem.Name
Debug.Print Intersect(pvtItem.DataRange.EntireRow, pvtNetField.DataRange).Value
Next pvtItem
End Sub
I didn't refer to this great VBA pivot table reference by Jon Peltier, but if you do you may find a better way.

Related

VBA "Error 1004: unable to get the PivotFields property of the PivotTable class "

I made a PQ append query, send reults to Data Model and then uploaded the pivot table to the excel sheet. Now I'm trying to apply filter based on the cell value.
Here's my code:
Sheets("RE_2").Select
Dim SK
Dim re_outcome
Dim re_income
SK = Range("I2").Value * 1
re_outcome = Range("H4").Value
re_income = Range("H5").Value
ActiveSheet.PivotTables("outcome_re_1").PivotFields("[RE_total_from_IR6].[entity].[entity]").ClearAllFilters
ActiveSheet.PivotTables("outcome_re_1").PivotFields("[RE_total_from_IR6].[entity].[entity]").CurrentPageName = SK
The last row produces an Error 1004: unable to get the PivotFields property of the PivotTable class .
I tried to change CurrentPageName to CurrentPage but got the same error.
I appreciate any help on the described error.
P.s.
I used debugger to find PivotFields with this code:
Dim pt As PivotTable
Dim pf As PivotField
Set pt = Worksheets("RE_2").PivotTables("outcome_re_1")
For Each pf In pt.PivotFields
Debug.Print pf.Name
Next
The output was as follows:
[RE_total_from_IR6].[entity].[entity]
[RE_total_from_IR6].[type].[type]
[RE_total_from_IR6].[bank].[bank]
The error is because no PivotField exists with the name "[RE_total_from_IR6].[entity].[entity]". The PivotFields name must match the name in the header of the pivot table. It should be the same as the PivotField.Caption property. Try using the debugger to look for the correct name of the PivotField.
I managed to make the code work by changing the last line of code that triggered the 1004 error.
I changed
ActiveSheet.PivotTables("outcome_re_1").PivotFields("[RE_total_from_IR6].[entity].[entity]").CurrentPageName = SK
to
ActiveSheet.PivotTables("outcome_re_1").PivotFields("[RE_total_from_IR6].[entity].[entity]").CurrentPageName = "[RE_total_from_IR6].[entity].&[" & SK & "]"

Use VBA to Set Pivot Table to Specific Date Based on Another Field

I have tried many iterations that I have found on the web but cannot get this to work. I have a pivot table that I need to update weekly and I need the date to be set to a variable base on a field in the worksheet. The date is a filter. Using the code below, I can change the date to a specific date.
Sub Macro7()
'
ActiveSheet.PivotTables("PivotTable2").PivotFields("[Test_Data].[Date].[Date]" _
).ClearAllFilters
ActiveSheet.PivotTables("PivotTable2").PivotFields("[Test_Data].[Date].[Date]" _
).CurrentPageName = "[Test_Data].[Date].&[2020-07-12T00:00:00]"
End Sub
However, when I try to set the date to a variable such as a string that points to the worksheet cell containing the date, it errors out, normally stating 'Unable to set the CurrentPage property of the PivotField class'. I have tried many different options and different code but nothing has worked. D2 is where the date is that changes. It updates based on a formula. I have tried also just hard coding the dates in the cell but that does not work either. Have also tried matching up date formats to the pivot, did not help. The field pulls the date of the last Friday, if that matters. I would be fine putting that into the code instead, if that would help (I tried, I got an error that the string could not be converted to the date).
Sub My_macro()
Dim str As String
str = ActiveSheet.Range("d2")
ActiveSheet.PivotTables("PivotTable2").PivotFields("[Test_Data].[Date].[Date]" _
).ClearAllFilters
ActiveSheet.PivotTables("PivotTable2").PivotFields("[Test_Data].[Date].[Date]").CurrentPage = str
End Sub
Can someone please tell me how to correct this? Have been trying for hours and hours and just cannot get it figured. Thanks. PS--I tried to upload a sheet, but I cannot figure out how, looks like I can only do pictures, so I uploaded that. Below is the pivot where the date filter is the issue, and below that is a sample of what feeds the pivot.
Edit: Have shared a sample of the file here:
https://www.dropbox.com/sh/4tzrrue0mggf6om/AAAd6024feSdc9MbCd9IZD0Wa?dl=0
When you record a macro you will get something like this
Sub Macro1()
'
' Macro1 Macro
'
'
ActiveSheet.PivotTables("PivotTable2").PivotFields("[_Data].[Date].[Date]"). _
ClearAllFilters
ActiveSheet.PivotTables("PivotTable2").PivotFields("[_Data].[Date].[Date]"). _
CurrentPage = "[_Data].[Date].&[2019-08-16T00:00:00]"
End Sub
Even though the macro gave you that code, it will error out if you directly ran it without changing anything.
Solution: This is a very old problem which can be fixed by changing CurrentPage to CurrentPageName
Now changing it to suit your need...
Sub Sample()
Dim ws As Worksheet
Set ws = Sheet1
Dim rngDt As Range
Set rngDt = ws.Range("D2")
Dim dtString As String
dtString = Format(rngDt.Value2, "yyyy-mm-dd")
Dim pt As PivotTable
Set pt = ws.PivotTables("PivotTable2")
Dim pf As PivotField
Set pf = pt.PivotFields("[_Data].[Date].[Date]")
pf.ClearAllFilters
pf.CurrentPageName = "[_Data].[Date].&[" & dtString & "T00:00:00]"
End Sub
EDIT
May I ask you...how can I select
MULTIPLE pivots on the same sheet and do this to their filters as
well, picking the same date (cell D2) for all of them? Just repeat the
code down, subbing in the names, or would something like an array
work? Thank you again, marking yours as the answer! –
learningthisstuff 2 days ago
You can do that in loop. For each pt in
ws.PivotTables and then For each pf in pt.PivotFields :) – Siddharth
Rout 2 days ago
Thanks....where do I put those lines? I tried a couple of places I
thought made sense but keep getting errors. I will keep trying
options, wondering if I need to remove the 'set pt/pf' lines? Thank
you. – learningthisstuff 14 hours ago >
Do they have the same field "Date"? – Siddharth Rout 13 hours ago
Yes, they are all almost identical. Same filters. – learningthisstuff 11 hours ago
You can try something like this (Untested)
Sub Sample()
Dim ws As Worksheet
Set ws = Sheet1
Dim rngDt As Range
Set rngDt = ws.Range("D2")
Dim dtString As String
dtString = Format(rngDt.Value2, "yyyy-mm-dd")
Dim pt As PivotTable
Dim pf As PivotField
For Each pt In ws.PivotTables
Set pf = pt.PivotFields("[_Data].[Date].[Date]")
pf.ClearAllFilters
pf.CurrentPageName = "[_Data].[Date].&[" & dtString & "T00:00:00]"
Next pt
End Sub
EDIT
As requested by OP's edit to this answer, since there are multiple pivots, the following changes to the above code was finally made.
Sub Sample2()
Dim ws As Worksheet
Set ws = Worksheets("Sheet1")
Dim rngDt As Range
Set rngDt = ws.Range("F32")
Dim dtString As String
dtString = Format(rngDt.Value2, "yyyy-mm-dd")
Dim pt As PivotTable
Dim pf As PivotField
For Each pt In ws.PivotTables
If pt = "PivotTable2" Then
Set pf = pt.PivotFields("[_Data].[Date].[Date]")
pf.ClearAllFilters
pf.CurrentPageName = "[_Data].[Date].&[" & dtString & "T00:00:00]"
Else
Set pf = pt.PivotFields("[Sales_Data].[Date].[Date]")
pf.ClearAllFilters
pf.CurrentPageName = "[Sales_Data].[Date].&[" & dtString & "T00:00:00]"
End If
Next pt
End Sub
EDIT: Never worked with cubefields, but this seems to do what you want:
Sub My_macro()
Dim dt As Date, pt As PivotTable, pf As PivotField
dt = ActiveSheet.Range("d2")
Set pt = ActiveSheet.PivotTables(1)
Set pf = pt.PageFields("[_Data].[Date].[Date]")
With pf
.ClearAllFilters
.CubeField.EnableMultiplePageItems = True
.VisibleItemsList = _
Array("[_Data].[Date].&[" & Format(dt, "yyyy-mm-dd") & "T00:00:00]")
End With
End Sub

Pivottable' s content format

everyone,
In this pivottable I'm working on, the source data has money values and quantities. I have a filter in my pivottable in order to choose what type of data I want to see in my pivottable, whether is "V" or "Q".
My problem is that I need to format the contents of the pivottable accordingly to the type of information I'm seeing: for money values, I need to see the contents in "# ###.00 €" format; for quantity values, in "#,##0".
I already tried to use a DataRange property for the pivotfields (as you can see in the code) and even tried using NumberFormat directly on the pivotfields, but none of these worked.
Do you suggest anything to solve this?
Dim vp As Workbook
Dim type_qv As String
Dim chart_pt As PivotTable
Dim pf As PivotField
Set vp = ThisWorkbook
Set chart_pt = vp.Sheets("Chart").PivotTables("VP_table")
'this detects what type of data is being used
type_qv = vp.Sheets("Chart").Range("B2").Value
If type_qv = "Q" Then
For Each pf In chart_pt.RowFields
pf.DataRange.NumberFormat = "#,##0"
Next
End If
If type_qv = "V" Then
For Each pf In chart_pt.RowFields
pf.DataRange.NumberFormat = "# ###.00 €"
Next
End If
It's "Sum of Q" but you don't want to look at the description because they can change it and they can move the table and they can show both fields.
Dim chart_pt As PivotTable, df As PivotField
Set chart_pt = ActiveSheet.Range("A3").PivotTable
For Each df In chart_pt.DataFields
Select Case True
Case df.Name Like "*Q"
df.DataRange.NumberFormat = "#,##0"
Case df.Name Like "*V"
df.DataRange.NumberFormat = "# ###.00 €"
Case Else
df.DataRange.NumberFormat = "# ###.00"
End Select
Next

Excel VBA - Filter specific data in Pivot Table

I tried using the code that appeared to have helped the poster at
Excel VBA - Privot table filter multiple criteria
But I keep on getting the following error: Unable to get the PIvtoFields property of the PIvotTable Class.
Sub FilterPivotItems()
Dim PT As PivotTable
Dim PTItm As PivotItem
Dim FiterArr() As Variant
' use an array to select the items in the pivot filter you want to keep visible
FiterArr = Array("MC. Santa Clara", "MC. Plaza Américas", "MC. El Frutal")
' set the Pivot Table
Set PT = ActiveSheet.PivotTables("PivotTable4")
' loop through all Pivot Items in "Value" Pivot field
For Each PTItm In PT.PivotFields("Value").PivotItems
If Not IsError(Application.Match(PTItm.Caption, FiterArr, 0)) Then ' check if current item is not in the filter array
PTItm.Visible = True
Else
PTItm.Visible = False
End If
Next PTItm
End Sub
What can I do?
After reading about the properties of the class, I finally got to what I wanted.
Sub filterpivot()
Dim pi As PivotItem
Dim pt As PivotTable
Dim first As String
Dim second As String
Dim third As String
Dim fourth As String
first = Range("a26").Value
second = Range("a27").Value
third = Range("a28").Value
fourth = Range("a29").Value
Set pt = Worksheets("Lowest Scores").PivotTables("PivotTable4")
With pt.PivotFields("Nombre conjunto")
For Each pi In pt.PivotFields("Nombre conjunto").PivotItems
If pi.Name = first Or pi.Name = second Or pi.Name = third Or pi.Name = fourth Then
pi.Visible = True
Else
pi.Visible = False
End If
Next pi
End With
End Sub
This bases the applied filter on specific cell values. My apologies if anyone was working on this already, I was on a crunch at work and needed the answer.

Why does using Rows.Count only find the first 12 rows of data?

I'm trying to find the rows with data in my source data sheet and then copy some of the columns into various places in my destination worksheet using VBA. I have successfully done this for a list with 12k lines but when I do some test data, it only copies the first 12 rows out of 19 rows of data....
Sub Header_Raw()
Dim dataBook As Workbook
Dim Header_Raw As Worksheet, Header As Worksheet
Dim dataSource As Range, dataDest As Range
Dim sourceDataRowCount As Integer, index As Integer
Set dataBook = Application.ThisWorkbook
Set sheetSource = dataBook.Sheets("Header_Raw")
Set sheetDest = dataBook.Sheets("Header")
Set dataSource = sheetSource.Range("B4", _
sheetSource.Range("J90000").End(xlUp))
sourceDataRowCount = dataSource.Rows.Count
Set dataDest = sheetDest.Range("B13", "B" & _
sourceDataRowCount)
For index = 1 To sourceDataRowCount
dataDest(index, 1).Value = dataSource(index, 1).Value
dataDest(index, 2).Value = dataSource(index, 2).Value
Next index
End Sub
If you can help tell me what I have done wrong, that would be great
thanks
Julie
Make your life a bit easier with simple debugging. Run the following:
Sub HeaderRaw()
'Dim all the variables here
Set dataBook = Application.ThisWorkbook
Set SheetSource = dataBook.Sheets("Header_Raw")
Set sheetDest = dataBook.Sheets("Header")
Set dataSource = SheetSource.Range("B4", SheetSource.Range("J90000").End(xlUp))
SheetSource.Activate
dataSource.Select
End Sub
Now you will see what is your dataSource, as far as it is selected. Probably it is not what you expect.

Resources