尝试从一组数据中创建数据透视表。通常它第一次运行正常,但是如果你再次尝试运行它会抛出“无效的过程调用或参数”,当你单击调试代码时会突出显示以下问题。更改数据透视表的名称没有帮助。表2存在并填充了数据。 “数据摘要”表也存在且完全为空
ActiveWorkbook.PivotCaches.Create(SourceType:=xlDatabase, SourceData:= _
"Sheet2!R1C1:R1064C4", Version:=xlPivotTableVersion14).CreatePivotTable _
TableDestination:="Data-Summary!R5C1", TableName:="PivotTable4", _
DefaultVersion:=xlPivotTableVersion
整个代码如下:
Sub Macro1()
'
' Macro1 Macro
'
'
Columns("A:D").Select
ActiveWorkbook.PivotCaches.Create(SourceType:=xlDatabase, SourceData:= _
"Sheet2!R1C1:R1064C4", Version:=xlPivotTableVersion14).CreatePivotTable _
TableDestination:="Data-Summary!R5C1", TableName:="PivotTable15", _
DefaultVersion:=xlPivotTableVersion14
Sheets("Data-Summary").Select
Cells(5, 1).Select
ActiveWorkbook.ShowPivotTableFieldList = True
With ActiveSheet.PivotTables("PivotTable3").PivotFields("Site")
.Orientation = xlRowField
.Position = 1
End With
With ActiveSheet.PivotTables("PivotTable3").PivotFields("Channel")
.Orientation = xlColumnField
.Position = 1
End With
ActiveSheet.PivotTables("PivotTable3").AddDataField ActiveSheet.PivotTables( _
"PivotTable3").PivotFields("Cost"), "Count of Cost", xlCount
ActiveSheet.PivotTables("PivotTable3").PivotFields("Count of Cost"). _
Orientation = xlHidden
ActiveSheet.PivotTables("PivotTable3").AddDataField ActiveSheet.PivotTables( _
"PivotTable3").PivotFields("Revenue"), "Count of Revenue", xlCount
With ActiveSheet.PivotTables("PivotTable3").PivotFields("Count of Revenue")
.Caption = "Sum of Revenue"
.Function = xlSum
End With
ActiveWorkbook.ShowPivotTableFieldList = False
End Sub
答案 0 :(得分:4)
更改tabledestination以在工作表名称周围添加引号
TableDestination:="'Data-Summary'!R5C1"
也有一些代码是不必要的
Sub Macro1()
'
' Macro1 Macro
'
'
Dim PT As Excel.PivotTable
Set PT = ActiveWorkbook.PivotCaches.Create(SourceType:=xlDatabase, SourceData:= _
"Sheet2!R1C1:R1064C4", Version:=xlPivotTableVersion14).CreatePivotTable( _
TableDestination:="'Data-Summary'!R5C1", TableName:="PivotTable15", _
DefaultVersion:=xlPivotTableVersion14)
With PT
With .PivotFields("Site")
.Orientation = xlRowField
.Position = 1
End With
With .PivotFields("Channel")
.Orientation = xlColumnField
.Position = 1
End With
.AddDataField .PivotFields("Revenue"), "Sum of Revenue", xlSum
End With
End Sub
答案 1 :(得分:0)
对于我来说,此错误是在升级到较新版本的Excel之后发生的,因为在使用CreatePivotTable函数创建数据透视表时,它无法识别DefaultVersion参数xlPivotTableVersion15枚举。
这对我不起作用,与空格或目的地名称无关:
Workbooks(WorkbookName).PivotCaches(1).CreatePivotTable _
TableDestination:=DestinationString, TableName:=TableNameString, _
DefaultVersion:=xlPivotTableVersion15
这是工作版本:
Workbooks(WorkbookName).PivotCaches(1).CreatePivotTable _
TableDestination:=DestinationString, TableName:=TableNameString, _
DefaultVersion:=6