VBA枢轴字段

时间:2018-07-02 17:42:52

标签: excel vba excel-vba

尝试使用VBA从excel表中进行透视。我没有收到错误,一切正常,期望在数据透视表上添加字段。运行代码时,表上没有任何行。我想念的是什么会导致不添加分配的枢轴字段?

更新:
是不是因为我需要以某种方式确定pf是什么,我才开始接班?

Option Explicit

Sub MakeAPivotTable()

Dim pt As pivotTable 'Creates pivot table
Dim pc As PivotCache
Dim pf As PivotField
Dim pi As PivotItem
Dim PRange As Range 'Source data range
Dim lastRow As Long
Dim lastCol As Long
Dim DSheet As Worksheet
Dim PSheet As Worksheet

'Insert a New Blank Worksheet
On Error Resume Next
Application.DisplayAlerts = False
Worksheets("Metrics").Delete
Sheets.Add Before:=ActiveSheet
ActiveSheet.Name = "Metrics"
Application.DisplayAlerts = True
Set PSheet = Worksheets("Metrics")
Set DSheet = Worksheets("DataInsert")

'Defining Data Range. Taking the first cell of the data table and select uptp the last row and then up to the last column
lastRow = DSheet.Cells(Rows.Count, 1).End(xlUp).Row
lastCol = DSheet.Cells(1, Columns.Count).End(xlToLeft).Column
Set PRange = DSheet.Cells(1, 1).Resize(lastRow, lastCol)

'Create pivot cache. Defines Pivot Cache by using Data source and defines the cell address in the new worksheet to insert pivot table
Set pc = ActiveWorkbook.PivotCaches.Create(SourceType:=xlDatabase, SourceData:=PRange).CreatePivotTable(TableDestination:=PSheet.Cells(2, 2), TableName:="Reclass")

'Insert Pivot Table
Set pt = pc.CreatePivotTable(TableDestination:=PSheet.Cells(1, 1), TableName:="Reclass")

 'put the fields in

 With pt
 'add the fields
.PivotFields("PO Requester").Orientation = xlRowField
.PivotFields("Func Currency Amt").Orientation = xlColumnField
.PivotFields("Reason").Orientation = xlRowField
.PivotFields("Reclass Flag").Orientation = xlDataField

'go to classic view
.RowAxisLayout xlTabularRow

 End With

End Sub

0 个答案:

没有答案