![](/img/trans.png)
[英]Automatic Pivot Table in VBA - Error invalid procedure call or argument
[英]Invalid procedure call or argument error creating a pivot table in VBA
我在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
如果不存在,請嘗試下面的代碼在“Sheet6”中創建“PivotTable1”。 如果它已經創建(從過去的代碼運行),只需使用更新的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
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.