VBA数据透视表不执行任何操作

时间:2019-03-11 09:47:56

标签: excel vba pivot-table

我的数据透视表代码实际上什么也没做。它只是创建一个新工作表,而不创建数据透视表。 在我的工作簿中,我将有两张纸:一张包含数据,另一张包含数据透视表。 这是我的代码:

Sub InsertPivotTable()
'Macro By ExcelChamps

'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

'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")

'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(2, 2), _
TableName:="Pivot_table")

'Insert Blank Pivot Table
Set PTable = PCache.CreatePivotTable _
(TableDestination:=PSheet.Cells(1, 1), TableName:="Pivot_table")

With ActiveSheet.PivotTables("Pivot_table").PivotFields("data1")
        .Orientation = xlPageField
        .Position = 1
End With


ActiveSheet.PivotTables("Pivot_table").AddDataField ActiveSheet.PivotTables( _
        "Pivot_table").PivotFields("data2"), "Count of data2", xlCount

'Format Pivot Table
ActiveSheet.PivotTables("Pivot_table").ShowTableStyleRowStripes = True
ActiveSheet.PivotTables("Pivot_table").TableStyle2 = "PivotStyleMedium9"

End Sub

0 个答案:

没有答案