【发布时间】:2019-11-30 04:49:23
【问题描述】:
我正在尝试使用下面的代码在 Excel 2010 中创建数据透视表,但似乎无法正常工作。
它甚至创建了一个名为“数据透视表”的新选项卡,但实际上没有数据出现。我正在尝试使用的功能是我将 excel 中生成的报告中的数据复制到我的数据透视生成器上的一个选项卡中,按下一个按钮,它会创建数据透视表。这是我在 Excel Champs 上找到的代码,但该线程似乎已经死亡,没有问题的答案。
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 PTable = ActiveWorkbook.PivotCaches.Create _
(SourceType:=xlDatabase, SourceData:=PRange). _
CreatePivotTable(TableDestination:=PSheet.Cells(2, 2), _
TableName:="DefectsPivotTable")
'Insert Blank Pivot Table
Set PTable = PCache.CreatePivotTable _
(TableDestination:=PSheet.Cells(1, 1), TableName:="DefectsPivotTable")
'Insert Row Fields
With ActiveSheet.PivotTables("DefectsPivotTable").PivotFields("Assigned to").Orientation = xlRowField.Position = 1
End With
'Insert Column Fields
With ActiveSheet.PivotTables("DefectsPivotTable").PivotFields("Status").Orientation = xlColumnField.Position = 1
End With
'Insert Data Field
With ActiveSheet.PivotTables("DefectsPivotTable").PivotFields("Status").Orientation = xlDataField.Function = xlSum.NumberFormat = "#,##0".Name = "Revenue "
End With
'Format Pivot Table
ActiveSheet.PivotTables("SalesPivotTable").ShowTableStyleRowStripes = True
ActiveSheet.PivotTables("SalesPivotTable").TableStyle2 = "PivotStyleMedium9"
End Sub
【问题讨论】:
-
首先,注释掉/删除
On Error Resume Next。这样你就会看到代码中的什么(如果有的话)不起作用。就目前而言,这只会运行,但不会告诉您它可能在哪里以及为什么会失败。然后,提供一个minimal reproducible example 描述如何使用这个宏,以及示例数据。 -
插入行/列/数据字段的语法看起来不正确。您还使用了两次
PTable,而不是PTable和PCache。
标签: excel vba pivot-table