【发布时间】:2017-02-08 06:30:51
【问题描述】:
目标
按降序对数据透视表值进行排序。
方法
- 删除以前的数据透视表 (@987654322@)
- 设置新的数据透视表位置 (
target) - 创建 PivotCache (
pvtCache) - 部署数据透视表 (@987654325@)
- 添加数据透视表字段 (
pvt.PivotFields(_)) - 问题:按降序对数据透视表字段 (
PivotField("Base Expense")) 进行排序
代码
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
错误
“对象不支持此属性或方法”
@线
'Sort by largest !!!ERROR!!!
pvt.PivotField("Base Expense") _
.AutoSort xlDescending, "Base Expense"
问题
- 不确定为什么会抛出此错误。我搜索的文档让我相信这应该可以工作 (https://msdn.microsoft.com/en-us/library/office/ff834371.aspx)注意:ActiveSheet != 到数据透视表所在的工作表,但我认为这不会在这里造成问题
- 感谢任何有关代码重构的建议。
【问题讨论】:
标签: excel vba sorting pivot-table