在首先确认表“狗报告”包含A1:BB1
作为透视表的SourceData:= "Dog Report!R1C1:R243C54"
状态源数据从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
您确定工作表“Dog Report”包含来自“A1:BB1”的数据作为数据透视表的字段名吗? “SourceData:=”Dog Report!R1C1:R243C54“”表示源数据从表格“狗报告”中的“A1:BB243”开始。顺便说一句:应该更好'SourceData:=''狗报告'!R1C1:R243C54“'。由于它包含一个空格,因此请注意引号中的表名。 –
还要确保,还没有一个使用'TableName:=“PivotTable1”'的透视表。 –