我知道我会被标记为此,但现在就这样了。
我一直在浏览几个有关此错误的论坛和信息网站,但我无法找出问题所在。
错误是:
运行时错误'1004':无法获取数据透视表类的PivotFields属性
这发生在以下行: Sheets(“PivotTable1”)。数据透视表(“占用”).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
任何人都能告诉我上面有什么问题吗?
编辑:我发现了其他一些关于这种情况的提及。由于某种原因,当枢轴子过程是其他子过程的一部分时,枢轴场不识别数据中的标题。我还没有找到明确的理由,但相信它与刷新数据和数据有关。
答案 0 :(得分:0)
根据您到目前为止所说的内容,我认为您的LRow
和/或Lcol
变量是从错误的工作表设置的,因此您的源数据不是它应该的。试试这个:
Sub OccupancyPivot()
Dim SrcData As String
Dim wsSheet As Worksheet
Dim PTCache As PivotCache
Dim PT As PivotTable
'Determine the data range you want to pivot
SrcData = "'Raw Data'!" & Worksheets("Raw Data").Range("A1").CurrentRegion.Address(ReferenceStyle:=xlR1C1)
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 PT
With .PivotFields("Precinct")
.Orientation = xlRowField
.Position = 1
End With
With .PivotFields("Registration")
.Orientation = xlDataField
.Function = xlCount
End With
With .PivotFields("Captured Date")
.Orientation = xlColumnField
.Position = 1
End With
With .PivotFields("Captured Session")
.Orientation = xlColumnField
.Position = 2
End With
With .PivotFields("Location")
.Orientation = xlRowField
.Position = 2
End With
End With
'ActiveWorkbook.Sheets("PivotTable").Visible = xlSheetVeryHidden
End Sub