VBA数据透视表未创建,我也不知道为什么

时间:2020-04-27 15:54:55

标签: excel vba

我一直在尝试使用宏子程序制作数据透视表,但是我的代码无法正常工作。工作表已创建并命名,但保持为空。我尝试更改数据范围,就像在这里找到的另一个类似问题中所看到的那样,但这没有用。我试图使“形状按钮”创建大量数据的数据透视表。自从使用VBA以来已有一段时间,请原谅我的菜鸟问题和编码不佳。 任何帮助表示赞赏!

这是代码:

Sub InsertPivotTable()

'Declare Variables
Dim PSheet As Worksheet 'nova planilha pra tab dinamica
Dim DSheet As Worksheet 'planilha de dados da tab dinamica
Dim PCache As PivotCache 'nome do cache
Dim PTable As PivotTable 'nome pra tab dinamica
Dim PRange As Range 'tamanho da fonte de dados
Dim LastRow As Long
Dim LastCol As Long

'Insert a New Blank Worksheet

On Error Resume Next
Application.DisplayAlerts = False
Worksheets("TESTE TabDin").Delete
Sheets.Add Before:=ActiveSheet
ActiveSheet.Name = "TESTE TabDin"
Application.DisplayAlerts = True
Set PSheet = Worksheets("TESTE TabDin")
Set DSheet = Worksheets("GESTÃO ORDENS ESMAGAMENTO")

'Define Data Range

LastRow = DSheet.Cells(DSheet.Rows.Count, 1).End(xlUp).Row
LastCol = DSheet.Cells(16, DSheet.Columns.Count).End(xlToLeft).Column
Set PRange = DSheet.Cells(16, 1).Resize(LastRow, LastCol)

'Define Pivot Cache

Set PCache = ActiveWorkbook.PivotCaches.Create(SourceType:=xlDatabase, SourceData:=PRange). _
     CreatePivotTable(TableDestination:=PSheet.Cells(2, 2), TableName:="TBAutom")

'Insert Blank Pivot Table

Set PTable = PCache.CreatePivotTable(TableDestination:=PSheet.Cells(1, 1), TableName:="TBAutom")

'Insert Row Fields

With ActiveSheet.PivotTables("TBAutom").PivotFields("CLASSE")
.Orientation = xlRowField
.Position = 1
End With

With ActiveSheet.PivotTables("TBAutom").PivotFields("CENTRO TRAB.")
.Orientation = xlRowField
.Position = 2
End With

'Insert Column Fields

With ActiveSheet.PivotTables("TBAutom").PivotFields("SETOR")
.Orientation = xlColumnField
.Position = 1
End With

With ActiveSheet.PivotTables("TBAutom").PivotFields("REVISÃO")
.Orientation = xlRowField
.Position = 2
End With

'Insert Data Field

With ActiveSheet.PivotTables("TBAutom").PivotFields("TIPO")
.Orientation = xlDataField
.Position = 1
.Function = xlCount
.NumberFormat = "###"
.Name = "CONTAGEM DE ORDENS"
End With

'Format Pivot

TableActiveSheet.PivotTables("TBAutom").ShowTableStyleRowStripes = _
       TrueActiveSheet.PivotTables("TBAutom").TableStyle2 = "PivotStyleMedium9"

End Sub

0 个答案:

没有答案