这是我第一次尝试编写生成数据透视表的VBA代码。以下是我的代码,当我运行它时,我没有得到任何错误,并且生成了新的工作表,但看不到透视表。
谢谢!
On Error Resume Next
Application.DisplayAlerts = False
Worksheets("WorkCat PT").Delete
Sheets.Add Before:=ActiveSheet
ActiveSheet.Name = "WorkCat PT"
Application.DisplayAlerts = True
Set PSheet = Worksheets("WorkCat PT")
DSheet = ActiveSheet.Data
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)
Set PCache = ActiveWorkbook.PivotCaches.Create(SourceType:=xlDatabase, SourceData:=PRange)
Set PTable = PCache.CreatePivotTable(TableDestination:=DSheet.Cells(2, 16), TableName:="WorkCatPivotTable")
With ActiveSheet.PTable.PivotFields("Work Category")
.Orientation = xlRowField
.Position = 1
End With
With ActiveSheet.PTable.PivotFields("Total Cost")
.Orientation = xlColumnField
.Position = 1
End With
With ActiveSheet.PTable.PivotFields("Total Cost")
.Orientation = xlDataField
.Position = 1
.Function = xlSum
.NumberFormat = "$ #,##0"
.Name = "Work Category"
End With