【发布时间】:2016-12-21 09:38:56
【问题描述】:
我知道我会因此被扣分,但是就这样吧。
关于这个错误,我已经浏览了几个论坛和信息丰富的网站,但我无法找出问题所在。
错误是:
运行时错误“1004”:无法获取数据透视表类的 PivotFields 属性
这发生在以下行: With Sheets("PivotTable1").PivotTables("Occupancy").PivotFields("Precinct")
我看到参考资料表明该错误可能是因为该字段未称为“Precinct”。但是,我直接复制并粘贴了它,并确保代码“写入”了该特定标题。我就是想不通。这可能与刷新数据或数据透视表有关吗?有没有办法用单元格引用替换问题行中的“Precinct”?
代码是:
Sub OccupancyPivot()
Dim SrcData As Variant
Dim LRow As Long, LCol As Long
Dim wsSheet As Worksheet
Dim PTCache As PivotCache
Dim PT As PivotTable
'Determine the data range you want to pivot
LRow = Cells(Rows.Count, 1).End(xlUp).Row
LCol = Cells(1, Columns.Count).End(xlToLeft).Column
Set SrcData = Worksheets("Raw Data").Range("A1:" & Cells(LRow, LCol).Address(False, False))
Sheets.Add.Name = "PivotTable1"
Set PTCache = ActiveWorkbook.PivotCaches.Add(xlDatabase, SrcData)
Set PT = PTCache.CreatePivotTable(Sheets("PivotTable1").Range("A1"), "Occupancy")
'Create the headings and row and column orientation
With Sheets("PivotTable1").PivotTables("Occupancy").PivotFields("Precinct")
.Orientation = xlRowField
.Position = 1
End With
With Sheets("PivotTable1").PivotTables("Occupancy").PivotFields("Registration")
.Orientation = xlDataField
.Function = xlCount
End With
With Sheets("PivotTable1").PivotTables("Occupancy").PivotFields("Captured Date")
.Orientation = xlColumnField
.Position = 1
End With
With Sheets("PivotTable1").PivotTables("Occupancy").PivotFields("Captured Session")
.Orientation = xlColumnField
.Position = 2
End With
With Sheets("PivotTable1").PivotTables("Occupancy").PivotFields("Location")
.Orientation = xlRowField
.Position = 2
End With
'ActiveWorkbook.Sheets("PivotTable").Visible = xlSheetVeryHidden
End Sub
谁能告诉我上面有什么问题?
编辑:我发现其他一些关于这种情况的提及。由于某种原因,当数据透视子过程是其他子过程的一部分时,数据透视字段无法识别数据中的标题。我还没有找到明确的原因,但相信这与刷新数据透视和数据有关。
【问题讨论】:
-
如果将
msgbox PT.PivotFields("Precinct").Caption添加到导致错误的行之前,会返回什么? -
@Rory 当我将它放在 With 语句之前时,它只会出现上述错误。
-
那么源数据的字段名不正确。
-
@Rory 我也这么认为。即使我从源数据中复制并粘贴字段名称,错误仍然存在。显然,pivot 函数无法识别名称,但我不知道为什么。
-
启动此代码时是否激活了原始数据表?
标签: excel pivot-table vba