我有一个用例,其中我在数据透视表中过滤列值,然后更改数据透视表的值字段设置。我每次删除前一个表格时都会创建数据透视表和表格。我的问题是我无法在枢轴中反映出一栏,但总计中的值正确。我的代码如下:
Sub createPivotandFilter()
'Declare Variables
Dim PSheet As Worksheet
Dim DSheet As Worksheet
Dim PCache As PivotCache
Dim PTable As PivotTable
Dim PRange As Range
Dim LastRow As Long
Dim LastCol As Long
Dim pf As PivotField
Dim PItems As PivotItem
'Insert a New Blank Worksheet
On Error Resume Next
Application.DisplayAlerts = False
Worksheets("PivotTable").Delete
Sheets.Add Before:=ActiveSheet
ActiveSheet.Name = "PivotTable"
Application.DisplayAlerts = True
Set PSheet = Worksheets("PivotTable")
Set DSheet = Worksheets("Data_TB Detail")
'Define Data Range
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)
'Define Pivot Cache
Set PCache = ActiveWorkbook.PivotCaches.Create(SourceType:=xlDatabase, SourceData:=PRange). _
CreatePivotTable(TableDestination:=PSheet.Cells(3, 1), _
TableName:="VariancePivot")
'Insert Blank Pivot Table
Set PTable = PCache.CreatePivotTable _
(TableDestination:=PSheet.Cells(1, 1), TableName:="VariancePivot")
With ActiveSheet.PivotTables("VariancePivot")
.InGridDropZones = True
.RowAxisLayout xlTabularRow
End With
'Insert Column Fields
With ActiveSheet.PivotTables("VariancePivot").PivotFields("Period")
.Orientation = xlColumnField
.Position = 1
End With
With ActiveSheet.PivotTables("VariancePivot").PivotFields("LE")
.Orientation = xlColumnField
.Position = 2
End With
'Insert Row Fields
With ActiveSheet.PivotTables("VariancePivot").PivotFields("Mapped up 1st level")
.Orientation = xlRowField
.Position = 1
End With
With ActiveSheet.PivotTables("VariancePivot").PivotFields("Account")
.Orientation = xlRowField
.Position = 2
End With
With ActiveSheet.PivotTables("VariancePivot").PivotFields("Description")
.Orientation = xlRowField
.Position = 3
End With
'Insert Data Field
With ActiveSheet.PivotTables("VariancePivot").PivotFields("USD")
.Orientation = xlDataField
.Position = 1
.Function = xlSum
.NumberFormat = "#,##0"
.Name = "Sum of USD"
.Calculation = xlDifferenceFrom
.BaseField = "Period"
.BaseItem = "Jun 30,2018"
End With
'adding the filter
Set PTable = ActiveSheet.PivotTables("VariancePivot")
Set pf = PTable.PivotFields("Period")
PTable.RefreshTable
temp = pf.PivotItems.Count
For i = 1 To temp
If pf.PivotItems(i).Value = "Jun 30,2018" Or pf.PivotItems(i).Value = "Sep 30,2018" Then
pf.PivotItems(i).Visible = True
Else
pf.PivotItems(i).Visible = False
End If
Next
End Sub
非常感谢您的帮助。