我在excel VBA中记录了一个从另一个表创建数据透视表的宏。我不知道为什么我收到这个错误:“运行时错误'5'”程序调用或参数无效。“
有人能告诉我我做错了吗?
Sheets("Sheet1").Select
Range("A1").Select
Range(Selection, Selection.End(xlToRight)).Select
Range(Selection, Selection.End(xlDown)).Select
ActiveWorkbook.PivotCaches.Create(SourceType:=xlDatabase, SourceData:= _
"Table_FTE_Distributions4.24", Version:=xlPivotTableVersion15).CreatePivotTable TableDestination:= _
"'Sheet6'! R3C1", TableName:="PivotTable1", DefaultVersion:=15
答案 0 :(得分:0)
尝试使用以下代码创建" PivotTable1" in" Sheet6"如果它不存在。如果它已经创建(从过去的代码运行),只需使用更新的PivotCache
进行更新。
<强>代码强>
Option Explicit
Sub RefreshPivots()
Dim ShtPivot As Worksheet
Dim PivTbl As PivotTable
Dim PivCache As PivotCache
Dim Tbl As ListObject
Dim SrcRng As Range
' set the Pivot Sheet
Set ShtPivot = Worksheets("Sheet6")
' set the ListObject to "Table_FTE_Distributions4.24"
Set Tbl = Worksheets("Sheet1").ListObjects("Table_FTE_Distributions4.24")
' set the Pivot Caches SourceData
Set SrcRng = Tbl.Range
' set the Pivot Cache
Set PivCache = ThisWorkbook.PivotCaches.Create(SourceType:=xlDatabase, SourceData:=SrcRng)
' add this line in case the Pivot table doesn't exit >> first time running this Macro
On Error Resume Next
Set PivTbl = ShtPivot.PivotTables("PivotTable1") ' check if "PivotTable1" Pivot Table already created (in past runs of this Macro)
On Error GoTo 0
If PivTbl Is Nothing Then
' create a new Pivot Table in "Sheet6", start from Cell A3
Set PivTbl = ShtPivot.PivotTables.Add(PivotCache:=PivCache, TableDestination:=ShtPivot.Range("A3"), TableName:="PivotTable1")
Else
' just refresh the Pivot cache with the updated Range in "Table_FTE_Distributions4.24"
MsgBox "PivotTable1 already exists, onyl need to refresh the Pivot Cache"
PivTbl.ChangePivotCache PivCache
PivTbl.RefreshTable
End If
End Sub