Drilldown to specific Total in Excel 2013 - vba

Dear Fellow Stackoverflow-ians,
I come to you with another problem. I'm creating a drilldown on a varying PivotTable by VBA. I'm looking to drilldown on the Total cell always, and referring to it as i did in my code doesn't work when my PivotTable expands. How do i refer to a cell in my PivotTable without using a Cell-refering.
Code is as following:
Sheets("16-Compliancy-Extract").Select
Range("H14").Select
Selection.ShowDetail = True
Selection.Copy
H14 is the cell i'm referring to. Problem is that this Cell-"Adress" keeps changing when i'm dumping new data in to the PivotTable.
How do i name it decently?

Fixed it with this: Where it searches for the last filled cell in the same column as my GrandTotal, which i was trying to retreive.
Dim rng As Range
Dim pt As PivotTable
Set pt = Sheets("16-Compliancy-Extract").PivotTables("Draaitabel1")
Set rng = pt.ColumnRange
rng.Cells(rng.Cells.Count).End(xlDown).ShowDetail = True

Related

How to link cell value as a filter in PowerPivot Pivot Table in Excel?

I have two Pivot Table (PivotTable1 and PivotTable2) in Sheet PivotTables_Sheetand a cell that shows the year in Sheet YearInput. I tried to link the cell year (J4) in YearInput as a filter to all pivot tables in PivotTables Sheet.
But somehow my code doesn't work as expected. Anybody knows how to correct this code?
This is the code:
Private Sub Worksheet_Change(ByVal Target As Range)
If Not Target.Address = Range("J4").Address Then Exit Sub
Dim pt As PivotTable
Dim ptItem As PivotItem
On Error Resume Next
For Each pt In Worksheets("PivotTables_Sheet").PivotTables
With pt.PivotFields("Year for Sales")
If .EnableMultiplePageItems = True Then
.ClearAllFilters
End If
Set ptItem = .PivotItems(Target.Value)
If Not ptItem Is Nothing Then
.CurrentPage = Target.Value
End If
End With
Next
End Sub
Note: I use Excel 2010 and built the pivot tables using PowerPivot.
One way to do this without VBA is to use a slicer which is common between all the pivots. Then one year is changed on one, it will also update the other pivot tables.
This is by first clicking on the pivot, which will then show on the ribbon an Analyze option. Under that there is an insert slicer, which you would do for year.
Afterwards you would go to your other pivots and instead do filter connection, and select your year slicer.
Note that the year slicer can then just be moved to a hidden sheet if you do not want the end user to see it, it will still do its job of propagating the year across all the pivots that are referencing it.

Entering formula into column range but select method of range class failed

please let me know if I need to be more specific. I am entering a weeknum() formula on my workbook isum on sheet stock. I want this formula to be evaluated for everything in the "X" column starting at row 2 since the top row will be a label. I used a macro recorder, but I am getting an error 1004 because my "select method of range class failed". There is probably a better way of writing this code. After, I want to make any weeknum value that is less than 27 in this column "Past". isum is my workbook and stock is my sheet in this workbook. I just made the range up to a certain amount rather than the used amount that I want to have. Here is my code so far: isum.Sheets("stock").Range("X2").Select
ActiveCell.FormulaR1C1 = "=WEEKNUM(RC[-9])"
Selection.AutoFill Destination:=Range("X2:X900").Select
Range("X2:X900").Select
Your code could be simplified to:
'Declare variables
dim wb as Workbook
dim ws as Worksheet
dim rng as Range
'Set variables
set wb = Workboooks("isum.xlsx") 'check the file extension & name is correct
set ws = wb.Worksheets("stock")
set rng = ws.range("X2:X900")
'Fill range with formula
rng.FormulaR1C1 = "=WEEKNUM(RC[-9])"
(Link - Here's a great reference on how/why to avoid using SELECT in VBA)
Edit: another way to set the workbook:
set wb = ThisWorkbook

Selecting data within a pivot table

I have some VBA code which needs to select Prod. Code, Lims#, SampleID, Log Date, District Name, Region, Machine ID, Ash, cNDF, CP, Ca, Cl from a pivot table.
When I use Entire row, I can select all the data that I need to make a clean paste into column A. However, now I'd like to paste into column
.PivotItems(PivotFieldName.Caption).DataRange.EntireRow.Select
I've attempted to do just data range, however it won't pull Prod.Code, Lims#, etc columns. It will only grab the analyte columns.
.PivotItems(PivotFieldName.Caption).DataRange.Select
I also tried to do a range off of the EntireRow, however then I can't figure out how to get last column or last row for that selected Prod. Code.
.PivotItems(PivotFieldName.Caption).DataRange.EntireRow.Range("A1:BB1").Select
How can I got about getting all columns for a Prod. code selected like the Entire Row method excluding the extra rows?
The Prod.Code Columns & Rows can shift in size depending on the data so I need to make it capable of grabbing the right range.
Further code structure:
Dim PvtTbl As PivotTable
Dim PvtFld As PivotField
Set PvtTbl = Sheets("NEP Pivot").PivotTables("NEP_Pivot")
Set PvtFld = PvtTbl.PivotFields("Prod. Code")
For Each PivotFieldName In PvtFld.PivotItems
'PivotFieldName.Caption represents "EHB"
If IsError(Application.Match(PivotFieldName.Caption, rngList, 0)) Then
With PvtFld
On Error Resume Next
.PivotItems(PivotFieldName.Caption).ShowDetail = True 'Show pivot item
.PivotItems(PivotFieldName.Caption).DataRange.EntireRow.Copy
Destination:=Sheets(PivotFieldName.Caption).Range("A3")
...
..
.
Use the .DataBodyRange property instead to get all the data within the pivot
PivotTable.DataBodyRange Property (Excel)
Returns a Range object that represents the range of values in a
PivotTable. Read-only.
Syntax
expression . DataBodyRange
expression A variable that represents a PivotTable object.
As you also want the row element you can do the following you can resize the data body range according to the difference in column count between the larger TableRange2 property and that inside pivot area. Be aware that grand totals etc may affect this but this shows you how to start thinking about it. There is also a TableRange1 property available with pivots.
Example pivot:
Code:
Option Explicit
Sub test()
Dim ws As Worksheet
Dim pvt As PivotTable
Dim columnsDifference As Long
Set ws = ActiveSheet
Set pvt = ws.PivotTables("PivotTable4")
columnsDifference = pvt.TableRange2.Columns.Count - pvt.DataBodyRange.Columns.Count
With pvt.DataBodyRange
Debug.Print .Offset(, -columnsDifference).Resize(.Rows.Count, .Columns.Count + columnsDifference).Address
End With
End Sub
I would recommend reading up on referencing pivottable ranges in VBA.
There are a variety of properties that you can use to determine ranges e.g. LabelRange and DataRange for fieldItems. You seems to have explored some of these. My experience has been that these are influenced by your pivottable layout and you will need to determine the current combination of methods to get your data.
For example, I used the following to get all the data for EHB with data laid out as follows:
Option Explicit
Sub test()
Dim ws As Worksheet
Dim pvt As PivotTable
Dim columnsDifference As Long
Dim wb As Workbook
Set wb = ThisWorkbook
Set ws = wb.Worksheets("mySheetName")
Set pvt = ws.PivotTables("NEP_Pivot")
columnsDifference = pvt.TableRange2.Columns.Count - pvt.DataBodyRange.Columns.Count
With pvt.DataBodyRange
Debug.Print pvt.PivotFields("Prod. Code").PivotItems("EHB").LabelRange.Offset(-1, 0).Resize(pvt.PivotFields("Prod. Code").PivotItems("EHB").LabelRange.Rows.Count, .Columns.Count + columnsDifference).Address
End With
End Sub
This produced the result
$C$11:$N$13
Notice how I have had to combine functions to get this result and if the pivottable layout gets changed this falls apart.
I was also able to write using:
With pvt.TableRange1
Debug.Print pvt.PivotFields("Prod. Code").PivotItems("EHB").LabelRange.Resize(pvt.PivotFields("Prod. Code").PivotItems("EHB").LabelRange.Rows.Count, .Columns.Count).Offset(-1, 0).Address
End With

Run time error -2147024809 (80070057) - Pivot Table field name is not valid

Got another Excel VBA Macro button issue.
I am trying to make a button to refresh all pivots on a worksheet (there are four). I have been to StackOverflow before and received a solution that worked well. I took the code I was provided before and updated it for the new workbook but it fails below with the function .ChangePivotCache PvtCache:
Sub Button1_Click()
Dim PvtTbl As PivotTable
Dim PvtCache As PivotCache
Dim PvtDataRng As Range
Set PvtDataRng = Worksheets("OTR_Promo_List_ADV_2017").Range("B2:AU500")
Set PvtCache = ActiveWorkbook.PivotCaches.Add(xlDatabase, PvtDataRng)
Set PvtTbl = Worksheets("Desired_Distribution").PivotTables("PivotTable1")
For Each PvtTbl In Worksheets("Desired_Distribution").PivotTables
Set PvtCache = ActiveWorkbook.PivotCaches.Add(xlDatabase, PvtDataRng)
With PvtTbl
.ChangePivotCache PvtCache
.RefreshTable
End With
Set PvtCache = Nothing
Next PvtTbl
End Sub
The only differences are that the workbook changed and now I want to refresh 4 pivots instead of 2 - could that be the issue?
Below a screenshot so you can see the worksheets. "OTR_Promo_List_ADV-2017" is the database. The Pivot tables have the default naming, I did not change the names (i.e. PivotTable1, PivotTable2...)
Thanks!
The code you use to refresh all pivot tables on the one sheet seems overly complex. I don't quite understand why you would want to use .ChangePivotCache at all. It changes the data source of the specified pivot table. If you just want to refresh a pivot table, that is completely unwarranted.
You can use Excel Table objects as the data source for your pivot tables, then a simple refresh will suffice. Or, if you don't want to use Tables (though you may really want to look into that, for obvious reasons), you can use dynamic range names to define the pivot source. With both techniques, you only need to refresh the pivot table and don't have to manipulate the pivot cache with VBA.
With Tables or dynamic range names as the source of pivot tables, you can refresh all pivot tables on a sheet by cycling through them and refresh them with codes along these lines:
Sub RefreshPivotsOnSheet()
Dim ws As Worksheet
Dim pt As PivotTable
Set ws = Worksheets("MySheet")
For Each pt In ws.PivotTables
pt.RefreshTable
Next pt
End Sub
Edit: How to set Excel Tables as the data source for a pivot: Turn the source data into a table with Ctrl + T or Insert > Table. Then edit the Pivot Table data source and point it to the Excel table you just created.
I was able to close this topic. I found somewhere else a simple macro that says only:
Sub REFRESH()
'
' REFRESH Macro
'
'
ActiveWorkbook.RefreshAll
End Sub
seemed to do the trick.
Thank you for all your inputs!

select range for Pivot in VBA

I want to create a macro for Pivot table with dynamic range. Pivot table is already made , I am just want to make Dynamic range selection macro. Range is A2:L
Please help Me how to create macro for just range selection and refresh All.
Sum of Amount in Document Currency Document Currency
Company Code Trading Partner BGN EUR
BG05 CH10 272,326.08 1,618.00
HS03 RS31 1,618.00
Below code is Woking for me. Got resolution.
Sub ChangeCaches()
Dim PT As PivotTable
Set PT = Sheets("OPEN ITEMS DETAIL").PivotTables("PivotTable1")
PT.SourceData = Sheets("Download").Range("A1").CurrentRegion.Address(True, True, xlR1C1, True)
End Sub