我不断收到此错误: 运行时错误“5”:
无效的过程调用或参数:
我刚刚学习VBA...是的,在我尝试问这个问题之前,我已经在这里搜索了答案。首先,我尝试向 TableDestination 添加单引号(但是工作表名称中没有空格),然后我尝试刷新我所做的表,没有。我还确保数据透视表名称是唯一的并且以前没有使用过,最后我遇到了一个解决方案来删除 Sheets.Add 语句并保留 TableDestination:=""。这有效,但是当我生成报告时,它会在 Excel 数据之前插入数据透视表,而我想要相反的方式,我确信我做错的事情非常简单,但我似乎找不到我想要的东西需要
Sub PostProcessing()
Dim MainWorksheet As Worksheet
Set MainWorksheet = ActiveWorkbook.Worksheets("Query1")
Dim pt As PivotTable
Dim pf As PivotField
Dim pi As PivotItem
Dim pc As PivotCache
Dim ws As Worksheet
With ActiveWorkbook
For Each pc In .PivotCaches
pc.MissingItemsLimit = xlMissingItemsNone
Next pc
End With
'Create a pivot table on page Two
Sheets.Add After:=Sheets(Sheets.Count)
ActiveWorkbook.PivotCaches.Create(SourceType:=xlDatabase, _
SourceData:= "Query1!R1C7:R90C8", _
Version:=xlPivotTableVersion14).CreatePivotTable _
TableDestination:="Sheet1!R1C1", TableName:= "PTCtable"
With ActiveSheet.PivotTables("PTCtable")'
With .PivotFields("Assigned To")
'Set the Row Field
.Orientation = xlRowField
.Position = 1
End With
ActiveSheet.Shapes.AddChart.Select
ActiveChart.ChartType = xlColumnClustered
End With
End Sub
您的问题与工作表的名称无关,您只是没有以正确的方式调用函数。 您想要创建一个数据透视表,但没有为其指定任何名称:您错过了等式的左侧部分。以下必须有效。
pc = ActiveWorkbook.PivotCaches.Create(SourceType:=xlDatabase,
SourceData:="Query1!R1C7:R90C8", Version:=xlPivotTableVersion14)
pt = pc.CreatePivotTable(TableDestination:="Sheet1!R1C1",TableName:="PTCtable")
如果没有,请尝试:
Set pc = ActiveWorkbook.PivotCaches.Create(SourceType:=xlDatabase,
SourceData:="Query1!R1C7:R90C8", Version:=xlPivotTableVersion14)
Set pt = pc.CreatePivotTable(TableDestination:="Sheet1!R1C1",TableName:="PTCtable")
所以我使用了一些@jamesC 的建议,并使用了表数据的范围,这让它正常工作。我确信某些代码可能不是最有效的,因为我对这门语言还很陌生,但以下是我所做的:(欢迎任何改进建议)
Dim pt As PivotTable
Dim pf As PivotField
Dim pi As PivotItem
Dim pc As PivotCache
With ActiveWorkbook
For Each pc In .PivotCaches
pc.MissingItemsLimit = xlMissingItemsNone
Next pc
End With
'Create a pivot table on page Two
ActiveWorkbook.Sheets.Add After:=Worksheets(Worksheets.Count)
ActiveWorkbook.PivotCaches.Create(SourceType:=xlDatabase, _
SourceData:="Query1!R1C7:R90C8", _
Version:=xlPivotTableVersion14).CreatePivotTable _
TableDestination:=Sheets(2).Range("A1:B1"), TableName:="PTCtable"
With Sheets(2).PivotTables("PTCtable") '
With .PivotFields("Assigned To")
'Set the Row Field
.Orientation = xlRowField
.Position = 1
End With
Sheets(2).Select
ActiveSheet.Shapes.AddChart.Select
ActiveChart.ChartType = xlColumnClustered
End With