我编写了一个脚本来创建一个新的数据透视表,但是我为添加数据透视字段的部分不断收到运行时错误91.
感谢您的所有帮助!
我的代码
Sub CreatePT()
Dim pt As PivotTable
Dim PTCache As PivotCache
Dim PTF As PivotFields
Dim wb As Workbook
Dim wsData As Worksheet
Dim wsPT As Worksheet
Dim rngData As Range
'Set the worksheet that contains data source
Set wsData = Worksheets("Raw Data")
Set wsPT = Worksheets("Pivot Talble")
Set wb = ThisWorkbook
'Set source data range
Set rngData = wsData.Range("A1:G50")
Set PTCache = ActiveWorkbook.PivotCaches.Create(xlDatabase, "'Raw Data'!A$1$:K$20$")
Set pt = PTCache.CreatePivotTable(wsPT.Range("B3"))
'Add in Filters to Pivot Table
With pt
With pt.PivotFields("Month")
.Orientation = xlPageField
.Position = 1
End With
With pt.PivotFields("Cost")
.Orientation = xlColumnField
End With
End With
End Sub
答案 0 :(得分:0)
我修改了您设置PivotCache
和PivotTable
的方式,看来它们是您出错的原因。
不确定PivotTable
源数据在哪里?是“原始数据”工作表中的范围(“A1:G50”),还是范围(“A1:K20”)?您是否希望动态查找“原始数据”工作表中包含数据的最后一行?
如果在先前的代码运行中已经创建了PivotTable
,我还添加了一个陷阱过程,如果是,那么PivotTable
将只刷新自己。如果未创建PivotTable
(首次运行此代码),则会创建PivotTable
所有PivotFields
。
注意 :你有工作表(“Pivot Talble”),我认为它可能是一个错字,不应该是“数据透视表”吗?
Option Explicit
Sub CreatePT()
Dim pt As PivotTable
Dim PTCache As PivotCache
Dim PTF As PivotFields
Dim wb As Workbook
Dim wsData As Worksheet
Dim wsPT As Worksheet
Dim rngData As Range
'Set the worksheet that contains data source
Set wsData = Worksheets("Raw Data")
Set wsPT = Worksheets("Pivot Talble")
Set wb = ThisWorkbook
'Set source data range
Set rngData = wsData.Range("A1:G50")
'Set pivot cache
Set PTCache = ActiveWorkbook.PivotCaches.Create(SourceType:=xlDatabase, SourceData:=rngData, Version:=xlPivotTableVersion14)
' add this line in case the Pivot table doesn't exit >> first time running this Macro set PivotTable
On Error Resume Next
Set pt = wsPT.PivotTables("PivotTable 1") ' Pivot Table already created (from previous code runs)
On Error GoTo 0
' first time running this code >> create the Pivot Table
If pt Is Nothing Then
Set pt = PTCache.CreatePivotTable(wsPT.Range("B3"), "PivotTable 1")
'Add in Filters to Pivot Table
With pt
With .PivotFields("Month")
.Orientation = xlPageField
.Position = 1
End With
With .PivotFields("Cost")
.Orientation = xlColumnField
End With
End With
Else
' just refresh the Pivot cache with the updated Range (data in "Raw Data" sheet)
pt.ChangePivotCache PTCache
pt.RefreshTable
End If
End Sub