Sort PivotTable VBA - excel

OBJECTIVE
Sort Pivot Table Values by Descending order.
APPROACH
Delete previous PivotTable (PIVOT)
Set up new PivotTable location (target)
Create PivotCache (pvtCache)
Deply PivotTable (pvt)
Add PivotTable Fields (pvt.PivotFields(_))
ISSUE: Sort PivotTable field (PivotField("Base Expense")) in descending order
CODE
Sub createPivot()
Dim ws As Worksheet
Dim pvtCache As pivotCache
Dim pvt As pivotTable
Dim srcData As String
Dim lastRow As Long
Dim startPvt As String
Dim target As Worksheet
'Delete previous pivottable
Worksheets("PIVOT").PivotTables("PivotTable1").TableRange2.Clear
'Select pivot table data
Worksheets("CONSOLIDATED").Activate
Set ws = ActiveSheet
lastRow = ws.Cells(ws.Rows.Count, "A").End(xlUp).Row
srcData = ActiveSheet.Name & "!" & Range("A1:H" & lastRow).Address(ReferenceStyle:=xlR1C1)
'Set pivot table location
Set target = ThisWorkbook.Worksheets("PIVOT")
startPvt = target.Name & "!" & target.Range("A1").Address(ReferenceStyle:=xlR1C1)
'Create pivot cache
Set pvtCache = ActiveWorkbook.PivotCaches.Create( _
SourceType:=xlDatabase, _
SourceData:=srcData)
'Deploy pivot table
Set pvt = pvtCache.CreatePivotTable( _
TableDestination:=startPvt, _
TableName:="PivotTable1")
'Add Pivot Fields
pvt.PivotFields("Fiscal Year").Orientation = xlColumnField
pvt.PivotFields("Fiscal Year").Position = 1
pvt.PivotFields("Fiscal Month").Orientation = xlColumnField
pvt.PivotFields("Fiscal Month").Position = 2
pvt.PivotFields("Unit").Orientation = xlRowField
pvt.PivotFields("Unit").Position = 1
pvt.PivotFields("Project").Orientation = xlRowField
pvt.PivotFields("Project").Position = 2
pvt.PivotFields("Base Expense").Orientation = xlDataField
'Sort by largest !!!ERROR!!!
pvt.PivotField("Base Expense") _
.AutoSort xlDescending, "Base Expense"
End Sub
ERROR
"Object doesn't support this property or method"
# Line
'Sort by largest !!!ERROR!!!
pvt.PivotField("Base Expense") _
.AutoSort xlDescending, "Base Expense"
QUESTIONS
Unsure why this error is being thrown. I've searched documentation that leads me to believe this should work (https://msdn.microsoft.com/en-us/library/office/ff834371.aspx) NOTE: ActiveSheet != to the sheet the pivot table is on, but I dont think that should create an issue here
Any recommendations on code-refactoring is appreciated.

The problem you are having is that you are trying to sort the values in the data field. It doesn't know which other field to sort by.
The PivotField that you want to run the AutoSort method on is the field that you want sorted. The Field parameter of the method is the key that you want to sort it on.
In this case, you want something like this:
pvt.PivotField("Project") _
.AutoSort xlDescending, "sum of Base Expense"

Related

Can not create pivot table by VBA but I can manually create pivot table from same data source

Sub CreatePivot()
Dim NewSheet As Worksheet
Dim PTCache As PivotCache
Dim PT As PivotTable
Dim PTRange As Range
Dim FinalRow As Long
Dim FinalCol As Long
Set NewSheet = Workbooks("東京威力_樞紐分
析.xlsm").Sheets.Add(Before:=Workbooks("東京威力_樞紐分
析.xlsm").Worksheets(1))
NewSheet.Name = "Summary"
For Each PT In NewSheet.PivotTables
PT.TableRange2.Clear
Next PT
Set PTRange = getTable("Table1").Range
'Create PivotCaches
Set PTCache = Workbooks("東京威力_樞紐分
析.xlsm").PivotCaches.Create(SourceType:=xlDatabase,
SourceData:=PTRange.Address)
'Create PivotTable
Set PT =
PTCache.CreatePivotTable(TableDestination:=NewSheet.Cells(2,
2),tableName:="PivotTable1")
'ManualUpdate On
PT.ManualUpdate = True
PT.AddFields RowFields:=Array("Recharge BU", "Main Category"),
ColumnFields:="Recharge To"
With PT.PivotFields("Hours")
.Orientation = xlDataField
.Function = xlSum
.Position = 1
.NumberFormat = "#,##0.00"
.Name = "Total - Hours"
End With
'Calcu PivotTable
PT.ManualUpdate = False
PT.ManualUpdate = True
End Sub
-------------------------------------------------------------------------
Function getTable(tableName As String) As ListObject
Dim FinalRow As Long
With Workbooks("東京威力_樞紐分析.xlsm").Worksheets("原始資料")
On Error GoTo ErrorHandler
FinalRow = .Cells(Rows.Count, 1).End(xlUp).row
Set getTable = .ListObjects(tableName)
End With
Exit Function
ErrorHandler:
Debug.Print Err.Number; ":" & Err.Description
If getTable Is Nothing Then
Workbooks("東京威力_樞紐分析.xlsm").Worksheets("原始資料").ListObjects.Add(xlSrcRange,
Workbooks("東京威力_樞紐分析.xlsm").Worksheets("原始資料").Range("A1:AK" & FinalRow), , xlYes).Name = "Table1"
Set getTable = Worksheets("原始資料").ListObjects(tableName)
End If
Resume Next
End Function
Hi Folks, the Purpose of the code is to create pivot table.
But I Got Error Message
『The PivotTable field name is not valid. To create a PivotTable report, you must use data that is organized as a list with labeled columns. If you are changing the name of a PivotTable field, you must type a new name for the field』 when I created Pivot Table. (at the line==> PTCache.CreatePivotTable)
What could possibly go wrong ? Thanks
PS : I can manually create pivot table from same data source.
SourceData:=PTRange.Address will give us the cell address without the sheet name, e.g. $C$7:$G$17. This do not work for PT.
SourceData requires range reference with sheet name, e.g.
Therefore, it should be
SourceData:= PTRange.Parent.Name & "!" & PTRange.Address. But if your sheet name contain spaces, then it should be SourceData:= "'" & PTRange.Parent.Name & "'!" & PTRange.Address.
Since your data is contained in named-range Table1, using the name as the SourceData will be much much easier.

Pivot Table with Runtime Error '5' Invalid procedure call or argument

I copied a template to create a pivot table but adjusted it for a dynamic range due to reports being different in sizes at work. I keep getting Runtime Error '5' Invalid procedure call or argument as an error however when trying to create the pivot table from the pivot cache.
Can anyone please assist?
Thanks,
Dim sht As Worksheet
Dim pvtCache As PivotCache
Dim pvt As PivotTable
Dim StartPvt As String
Dim SrcData As Range
'Determine the data range you want to pivot
Set SrcData = Sheet1.Range("A1").CurrentRegion
'ActiveSheet.Name & "!" &
'Range("A1:R100").Address(ReferenceStyle:=xlR1C1)
'Create a new worksheet
Set sht = Sheets.Add
With sht
.Name = "Payments Balancing"
End With
'Where do you want Pivot Table to start?
StartPvt = sht.Name & "!" &
sht.Range("A1").Address(ReferenceStyle:=xlR1C1)
'Create Pivot Cache from Source Data
Set pvtCache = ActiveWorkbook.PivotCaches.Create( _
SourceType:=xlDatabase, _
SourceData:=SrcData)
'Create Pivot table from Pivot Cache
Set pvt = pvtCache.CreatePivotTable( _
TableDestination:=StartPvt, _
TableName:="PivotTable1")
End Sub

Excel macro Add-in duplicate spreadsheet pop up

My macro creates a pivot table from scratch from a set data dump. I am trying to move this macro to an add-in. the add-in works on the new data each time, but for some reason it pops up a second workbook that my code originally worked on.
I've read through add-in websites to make sure I set up the add-in correctly. My other add-in macro works (only have 2. still learning)
Sub OpenAndHoldPivot()
Dim sht As Worksheet
Dim pvtCache As PivotCache
Dim pvt As PivotTable
Dim StartPvt As String
Dim SrcData As String
'Determine the data range you want to pivot
Dim finRow As String
With ActiveWorkbook
finRow = ActiveSheet.Range("A200000").End(xlUp).Row
SrcData = ActiveSheet.Name & "!" & Range("A4:BO" & finRow - 1).Address (ReferenceStyle:=xlR1C1)
End With
'Create a new worksheet
Set sht = Sheets.Add
'Pivot Table Start
StartPvt = sht.Name & "!" & sht.Range("A3").Address(ReferenceStyle:=xlR1C1)
'Create Pivot Cache from Source Data
Set pvtCache = ActiveWorkbook.PivotCaches.Create( _
SourceType:=xlDatabase, _
SourceData:=SrcData)
'Create Pivot table from Pivot Cache
Set pvt = pvtCache.CreatePivotTable( _
TableDestination:=StartPvt, _
TableName:="PivotTable1")
'------------------------------------------------------------------------------
Set pvt = ActiveSheet.PivotTables("PivotTable1")
'Add item to the Report Filter
pvt.PivotFields("Future Fill Date").Orientation = xlPageField
'Add item to the Column Labels
pvt.PivotFields("Worker Type").Orientation = xlColumnField
'Add item to the Row Labels
pvt.PivotFields("Flex Division").Orientation = xlRowField
'Turn on Automatic updates/calculations --like screenupdating to speed up code
pvt.ManualUpdate = False
'------------------------------------------------------------------------------
ActiveSheet.Name = "Pivot"
'------------------------------------------------------------------------------
Dim pf As String
Dim pf_Name As String
pf = "FT/PT"
pf_Name = "Sum of FT/PT"
Set pvt = ActiveSheet.PivotTables("PivotTable1")
pvt.AddDataField pvt.PivotFields("FT/PT"), pf_Name, xlCount
'------------------------------------------------------------------------------
Dim pm As PivotField
Set pm = ActiveSheet.PivotTables("PivotTable1").PivotFields("Future Fill Date")
'Clear Out Any Previous Filtering
pm.ClearAllFilters
'Filter on 2014 items
pm.CurrentPage = "(blank)"
'------------------------------------------------------------------------------
Sheets("Sheet1").Name = "Data"
End Sub
Any ideas on what I am doing wrong?
I really think your problem lies with some inconsistent refernces (or lack of refernces) to which workbook or worksheet you're using. Specifically, I believe the problem is with the line
Set sht = Sheets.Add
Since your Sheets reference doesn't specify which workbook to add the new worksheet, it will default to the currently active workbook which could be your add-in workbook. You'll help yourself a great deal if you become much clearer about which workbooks and worksheets you want. To illustrate this using your example, you can start with
Sub OpenAndHoldPivot()
Dim workingWB As Workbook
Dim workingWS As Worksheet
Set workingWB = ActiveWorkbook
Set workingWS = activeworksheet
'Determine the data range you want to pivot
Dim srcData As Range
Dim srcDataText As String
With workingWS
Dim finRow As Long
finRow = .Cells(.Rows.Count, 1).End(xlUp).Row
Set srcData = .Range("A4").Resize(finRow - 1, 67)
srcDataText = .Name & "!" & srcData.Address(ReferenceStyle:=xlR1C1)
End With
This establishes clearly which workbook all your code will operate. Also, if you take a look at my With block and compare it to yours, you can see you missed a . before the Range reference, which again will likely refer back to either your add-in or the active workbook (and you can never be too sure.
After that, I just continue down the code...
'Create a new worksheet in the working workbook
Dim pivotWS As Worksheet
Set pivotWS = workingWB.Sheets.Add
'Pivot Table Start
Dim StartPvtText As String
StartPvtText = pivotWS.Name & "!" & pivotWS.Range("A3").Address(ReferenceStyle:=xlR1C1)
'Create Pivot Cache from Source Data
Dim pvtCache As PivotCache
Set pvtCache = ActiveWorkbook.PivotCaches.Create( _
SourceType:=xlDatabase, _
SourceData:=srcDataText)
'Create Pivot table from Pivot Cache
Dim pvt As PivotTable
Set pvt = pvtCache.CreatePivotTable( _
TableDestination:=StartPvtText, _
TableName:="PivotTable1")
Notice also that I declare all my variables as close to where they're used as possible. This makes it much easier to follow and to be certain you're using the correct variable with the intended type.
Further on down your code, you've referred to the ActiveSheet a few times. Replace that with a specific reference in order to be consistent. In my code, I rarely use ActiveSheet or ActiveCell. I attempted to fix the references below here in the full module, but only you can tell if this is accurate (because it's not perfectly clear which book or sheet you want).
Finally, there's the very last line of code Sheets("Sheet1").Name = "Data". I have no idea which workbook that should reference, but my guess is that it should be workingWB.Sheets("Sheet1").Name = "Data".
Option Explicit
Sub OpenAndHoldPivot()
Dim workingWB As Workbook
Dim workingWS As Worksheet
Set workingWB = ActiveWorkbook
Set workingWS = activeworksheet
'Determine the data range you want to pivot
Dim srcData As Range
Dim srcDataText As String
With workingWS
Dim finRow As Long
finRow = .Cells(.Rows.Count, 1).End(xlUp).Row
Set srcData = .Range("A4").Resize(finRow - 1, 67)
srcDataText = .Name & "!" & srcData.Address(ReferenceStyle:=xlR1C1)
End With
'Create a new worksheet in the working workbook
Dim pivotWS As Worksheet
Set pivotWS = workingWB.Sheets.Add
'Pivot Table Start
Dim StartPvtText As String
StartPvtText = pivotWS.Name & "!" & pivotWS.Range("A3").Address(ReferenceStyle:=xlR1C1)
'Create Pivot Cache from Source Data
Dim pvtCache As PivotCache
Set pvtCache = ActiveWorkbook.PivotCaches.Create( _
SourceType:=xlDatabase, _
SourceData:=srcDataText)
'Create Pivot table from Pivot Cache
Dim pvt As PivotTable
Set pvt = pvtCache.CreatePivotTable( _
TableDestination:=StartPvtText, _
TableName:="PivotTable1")
'------------------------------------------------------------------------------
Set pvt = pivotWS.PivotTables("PivotTable1")
'Add item to the Report Filter
pvt.PivotFields("Future Fill Date").Orientation = xlPageField
'Add item to the Column Labels
pvt.PivotFields("Worker Type").Orientation = xlColumnField
'Add item to the Row Labels
pvt.PivotFields("Flex Division").Orientation = xlRowField
'Turn on Automatic updates/calculations --like screenupdating to speed up code
pvt.ManualUpdate = False
'------------------------------------------------------------------------------
pivotWS.Name = "Pivot"
'------------------------------------------------------------------------------
Dim pf As String
Dim pf_Name As String
pf = "FT/PT"
pf_Name = "Sum of FT/PT"
Set pvt = pivotWS.PivotTables("PivotTable1")
pvt.AddDataField pvt.PivotFields("FT/PT"), pf_Name, xlCount
'------------------------------------------------------------------------------
Dim pm As PivotField
Set pm = pivotWS.PivotTables("PivotTable1").PivotFields("Future Fill Date")
'Clear Out Any Previous Filtering
pm.ClearAllFilters
'Filter on 2014 items
pm.CurrentPage = "(blank)"
'------------------------------------------------------------------------------
workingWB.Sheets("Sheet1").Name = "Data"
End Sub

Why am I receiving Run time error 5 Invalid procedure call or argument?

I receive the error when set the pivot cache. I.e at this line:-
Set pvt = pvtCache.CreatePivotTable(TableDestination:=StartPvt, TableName:="PivotTable2")
I have used this macro in another workbook and I have not received this error.
Sub PivTable()
'
' Insert a pivot table
'
Dim sht As Worksheet
Dim pvtCache As PivotCache
Dim pvt As PivotTable
Dim StartPvt As String
Dim SrcData As String
Dim ws As Worksheet
Dim x As Long
Set ws = Worksheets("Cash Month End")
With ws
x = .Range("b999999").End(xlUp).Row
End With
'Data Range to pivot
SrcData = "Cash Month End!(R4C1:R" & x & "C24)"
' Insert Sheet
Sheets.Add.Name = "Cash Pivot"
'Where the pivot must start
StartPvt = "Cash Pivot!R3C1"
'Create the pivot cache
Set pvtCache = ActiveWorkbook.PivotCaches.Create(SourceType:=xlDatabase, SourceData:=SrcData)
'Create Pivot Table from Pivot Cache
Set pvt = pvtCache.CreatePivotTable(TableDestination:=StartPvt, TableName:="PivotTable2")
'Add fields
With ActiveSheet.PivotTables("PivotTable2").PivotFields("Segment")
.Orientation = xlPageField
.Position = 1
End With
With ActiveSheet.PivotTables("PivotTable2").PivotFields("Region")
.Orientation = xlRowField
.Position = 1
End With
ActiveSheet.PivotTables("PivotTable2").AddDataField ActiveSheet.PivotTables( _
"PivotTable2").PivotFields("No."), "Sum of No", xlSum
End Sub

Excel create Pivot Table by VBA

I am creating a simple Pivot table by VBA. I don't know what is wrong with my code. My code runs without error but the results is different. Could you please tell me where is the problem in my code.
Sub CreatePivotTable()
Dim sht As Worksheet
Dim pvtCache As PivotCache
Dim pvt As PivotTable
Dim StartPvt As String
Dim SrcData As String
'Determine the data range you want to pivot
SrcData = ActiveSheet.Name & "!" & Range("A1:B53821").Address(ReferenceStyle:=xlR1C1)
'Create a new worksheet
Set sht = Sheets.Add
'Where do you want Pivot Table to start?
StartPvt = sht.Name & "!" & sht.Range("A1").Address(ReferenceStyle:=xlR1C1)
'Create Pivot Cache from Source Data
Set pvtCache = ActiveWorkbook.PivotCaches.Create(SourceType:=xlDatabase, SourceData:=SrcData)
'Create Pivot table from Pivot Cache
Set pvt = pvtCache.CreatePivotTable(TableDestination:=StartPvt, TableName:="PivotTable1")
pvt.PivotFields("Module").Orientation = xlRowField
pvt.PivotFields("KW").Orientation = xlColumnField
pvt.AddDataField pvt.PivotFields("Module"), "Anzahl von Module", xlCount
pvt.PivotFields("Module").PivotFilters.Add Type:=xlTopCount, DataField:=pvt.PivotFields("Anzahl von Module"), Value1:=12
End Sub
If I do it manually, this is the result I get and this is what I want at the end.
My code gives me this result. Which is wrong.
I think your problem is in your small initial range with only two columns (A, B) and the last lines of code
'Determine the data range you want to pivot
SrcData = ActiveSheet.Name & "!" & Range("A1:B53821").Address(ReferenceStyle:=xlR1C1)
Let's suppose you have your name in column A, call Module and column B is KW with a number (the KW/h of your module)
'Create Pivot table from Pivot Cache
Set pvt = pvtCache.CreatePivotTable(TableDestination:=StartPvt, TableName:="PivotTableTest")
pvt.AddDataField pvt.PivotFields("Module"), "Num Module", xlCount
pvt.PivotFields("Module").Orientation = xlColumnField ' not xlRowField
pvt.PivotFields("KW").Orientation = xlRowField ' not xlColumnField
You don't need the last line.
Try adding the xlRowField and xlColumnField after you added the calculated field.
e.g.
first
pvt.AddDataField pvt.PivotFields("Module"), "Anzahl von Module", xlCount
then
pvt.PivotFields("Module").Orientation = xlRowField
pvt.PivotFields("KW").Orientation = xlColumnField

Resources