【发布时间】:2013-09-02 15:41:20
【问题描述】:
我正在使用以下代码:
Sub MakeAPivotTable()
Dim pt As PivotTable
Dim cacheOfpt1 As PivotCache 'This is the Source Data
Dim pf As PivotField
Dim pi As PivotItem
Dim LastCol As Long
Dim LastRow As Long
Dim PRange As Range
LastCol = Sheets("Sheet2").Range("A1").SpecialCells(xlCellTypeLastCell).Column
LastRow = Sheets("Sheet2").Range("A1").SpecialCells(xlCellTypeLastCell).Row
Set PRange1 = Sheets("Sheet2").Cells(1, 1).Resize(LastRow, LastCol)
On Error GoTo err_add_Y_next_row
Sheets("Sheet3").Select
ActiveSheet.PivotTables("PivotTable1").TableRange2.Clear 'Delete any Pivot Table
'set the cache of PT
Sheets("Sheet2").Select
Set cacheOfpt1 = ActiveWorkbook.PivotCaches.Create(xlDatabase, PRange1)
'create the pt
Sheets("Sheet3").Select
Set pt = ActiveSheet.PivotTables.Add(cacheOfpt1, Range("a1"), "PivotTable1")
'put the Fields in
With pt
'add the Fields
.PivotFields("CAMPAIGN").Orientation = xlRowField
'.PivotFields("TAG1").Orientation = xlRowField
'.PivotFields("TAG2").Orientation = xlRowField
'.PivotFields("TAG3").Orientation = xlRowField
.PivotFields("CIRN").Orientation = xlColumnField
.PivotFields("RUN").Orientation = xlPageField 'Column Filter
.PivotFields("TVSN").Orientation = xlDataField 'Value Field
'set the number format
.DataBodyRange.NumberFormat = "#,##0.00"
'go to classic View
.RowAxisLayout xlTabularRow
End With
err_add_Y_next_row:
MsgBox Err.Number & Err.Description, _
vbExclamation, "VBAtools.pl"
End Sub
但是当我运行代码时,我收到错误“数据透视表字段名称无效。要创建数据透视表报表,您必须使用组织为带有标签列的列表的数据,如果您是要更改数据透视表字段的名称,您必须为该字段键入一个新名称。"
这段代码运行良好。但是突然间我开始收到这个错误。
谁能帮我找出原因。
谢谢。
【问题讨论】:
-
您检查了数据透视表名称吗? :-)
-
错误出现在哪一行?
-
@Makah:是的,我检查了数据透视表名称。
-
@Doug:“Set pt=" 行发生错误。
-
我怀疑您的源范围发生了问题,可能是列标题(或整个列?)被意外删除了?