首先确保工作表“Dog Report”包含来自A1:BB1 的数据作为数据透视表的字段名称。SourceData:= "Dog Report!R1C1:R243C54" 声明源数据来自工作表“Dog Report”中的A1:BB243。顺便说一句:参考应该更好SourceData:= "'Dog Report'!R1C1:R243C54"。请注意引号中的工作表名称,因为它包含一个空格。
还要确保工作表“宠物”中还没有带有TableName:= "PivotTable1" 的数据透视表。
为此,您可以编写代码:
Dim pvtTable As PivotTable
Dim bPivotTable1Exists As Boolean
With ActiveWorkbook
With .Worksheets("Pets")
For Each pvtTable In .PivotTables
If pvtTable.Name = "PivotTable1" Then
bPivotTable1Exists = True
End If
Next
End With
If Not bPivotTable1Exists Then
.PivotCaches.Create(SourceType:=xlDatabase, SourceData:= _
"'Dog Report'!R1C1:R243C54", Version:=xlPivotTableVersion14). _
CreatePivotTable TableDestination:="Pets!R2C1", TableName:= _
"PivotTable1", DefaultVersion:=xlPivotTableVersion14
Else
'do something if pivot table already exists
End If
End With
如果仍然失败,请确保工作表“宠物”不包含新数据透视表所需范围内的数据。但这不会引发错误,但会导致确认对话框。
此外:“宠物”表必须存在并且是工作表而不是图表表。
如果仍然失败,我将分两部分进行创建过程。一个用于数据透视缓存,另一个用于数据透视表。所以我们可以确定到底是什么失败了:
Dim pvtCache As PivotCache
Dim pvtTable As PivotTable
Dim bPivotTable1Exists As Boolean
With ActiveWorkbook
With .Worksheets("Pets")
For Each pvtTable In .PivotTables
If pvtTable.Name = "PivotTable1" Then
bPivotTable1Exists = True
End If
Next
End With
If Not bPivotTable1Exists Then
Set pvtCache = .PivotCaches.Create(SourceType:=xlDatabase, SourceData:= _
"'Dog Report'!R1C1:R243C54", Version:=xlPivotTableVersion14)
With .Worksheets("Pets")
.Range("A2:C19").ClearContents
End With
Set pvtTable = pvtCache.CreatePivotTable(TableDestination:="Pets!R2C1", TableName:= _
"PivotTable1", DefaultVersion:=xlPivotTableVersion14)
Else
'do something if pivot table already exists
End If
End With