[英]Runtime Error 5 : Excel VBA
我已經創建了一個宏,用於從數據表“ Sheet1”中的“數據透視表”中創建數據透視表。
盡管我可以在我的系統中運行宏,但在其他系統中卻可以在ActiveWorkbook.PivotCaches.Create
行中看到運行時錯誤5。
Sub Make_Pivot()
'
' Make_Pivot Macro
Sheets("Sheet1").Select
Columns("D:G").Select
Range("G1").Activate
ActiveWorkbook.PivotCaches.Create(SourceType:=xlDatabase, SourceData:= _
"Sheet1!R1C4:R1048576C7", Version:=6).CreatePivotTable TableDestination:= _
"Pivot!R1C1", TableName:="PivotTable1", DefaultVersion:=6
Sheets("Pivot").Select
Cells(1, 1).Select
With ActiveSheet.PivotTables("PivotTable1").PivotFields("NDL")
.Orientation = xlRowField
.Position = 1
End With
ActiveSheet.PivotTables("PivotTable1").AddDataField ActiveSheet.PivotTables( _
"PivotTable1").PivotFields("Tracking IDs"), "Count of Tracking IDs", xlCount
Columns("A:B").Select
Range("B1").Activate
Selection.Copy
Range("G13").Select
Sheets("Count").Select
Range("A1").Select
Selection.PasteSpecial Paste:=xlPasteValues, Operation:=xlNone, SkipBlanks _
:=False, Transpose:=False
Range("F18").Select
End Sub
嘗試下面的動態代碼(代碼內的注釋說明):
Option Explicit
Sub Make_Pivot()
' Make_Pivot Macro
Dim WB As Workbook
Dim ws As Worksheet
Dim PvtSht As Worksheet
Dim PvtTbl As PivotTable
Dim PvtCache As PivotCache
Dim SrcData As Range
Dim LastRow As Long
' set the workbook object
Set WB = ThisWorkbook
' set the worksheet object where the Pivot-Table will be
Set PvtSht = ThisWorkbook.Worksheets("Pivot")
' set the worksheet object where the Data lies
Set ws = ThisWorkbook.Worksheets("Sheet1")
With ws
LastRow = .Cells(.Rows.Count, "G").End(xlUp).Row ' <-- last row in column "G"
' set the Pivot-Cache SourceData object
Set SrcData = .Range("D1:G" & LastRow)
End With
' Create the Pivot Cache
Set PvtCache = WB.PivotCaches.Create(SourceType:=xlDatabase, _
SourceData:=SrcData.Address(False, False, xlA1, xlExternal))
' === FOR DEBUG ONLY ===
MsgBox PvtCache.SourceData
' Set the Pivot Table Object (already created in previous macro run)
On Error Resume Next
Set PvtTbl = PvtSht.PivotTables("PivotTable1")
On Error GoTo 0
If PvtTbl Is Nothing Then ' <-- pivot table still doesn't exist >> need to create it
' create a new Pivot Table in "Pivot" sheet, start from Cell A1
Set PvtTbl = PvtSht.PivotTables.Add(PivotCache:=PvtCache, TableDestination:=PvtSht.Range("A1"), TableName:="PivotTable1")
With PvtTbl
With .PivotFields("NDL")
.Orientation = xlRowField
.Position = 1
End With
.AddDataField .PivotFields("Tracking IDs"), "Count of Tracking IDs", xlCount
End With
Else
' just refresh the Pivot table, with updated Pivot Cache
PvtTbl.ChangePivotCache PvtCache
PvtTbl.RefreshTable
End If
' rest of your code goes here ...
End Sub
注意 :不需要使用那么多的Select
和Selection
,而是使用完全限定的Range
, Worksheet
和Object
。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.