2017-08-29 75 views
0

我需要創建數據透視表,但我試圖添加行字段但我得到錯誤爲「運行時錯誤'1004'無法獲得工作表類」運行時錯誤'1004'無法獲取工作表類的數據透視表屬性

On Error Resume Next 
    For Each WS In ActiveWorkbook.Worksheets 
     For Each PT In WS.PivotTables 
      WS.Range(PT.TableRange2.Address).Delete Shift:=xlUp 
     Next PT 
    Next WS 
Set Pvt = ActiveSheet.PivotTables("ZFIGLABACUS") 
ActiveCell.SpecialCells(xlLastCell).Select 
    Range(Selection, ActiveCell.SpecialCells(xlLastCell)).Select 
    ActiveWorkbook.PivotCaches.Create(SourceType:=xlDatabase, SourceData:= _ 
     "FBL5N!R1C1:R30000C14", Version:=xlPivotTableVersion14).CreatePivotTable _ 
     TableDestination:="SUMMARY!R3C9", TableName:="ZFIGLABACUS", DefaultVersion _ 
     :=xlPivotTableVersion14 
    Sheets("SUMMARY").Select 


    Pvt.PivotFields("G/L Account").Orientation = xlRowField 

我無法將行字段添加到其中,我會得到錯誤的樞軸的樞軸表屬性幫我出

+0

您正在刪除所有工作表中的所有數據透視表,當您重新創建數據透視表時,您不使用「Set Pvt = ActiveWorkbook.PivotCaches.Create ...」,因此您在以下行 –

+0

那麼現在我可以做什麼來消除錯誤,我應該刪除特定的以前的樞軸或其他任何東西。 – Nithin

+0

你想達到什麼目的?您正在刪除所有數據透視表,然後重新創建它們,爲什麼? –

回答

0

嘗試下面的代碼,說明內代碼評論:

Option Explicit 

Sub AutoPivotTable() 

Dim Sht As Worksheet 
Dim PvtSht As Worksheet 
Dim SrcData As Range 
Dim PvtCache As PivotCache 
Dim PvtTbl As PivotTable 

'-- Determine the data range you want to pivot -- 
' Set the Worksheet object 
Set Sht = ThisWorkbook.Worksheets("FBL5N") 
Set SrcData = Sht.Range("A1:M30000") 

' Set the Pivot Cache from Source Data 
Set PvtCache = ActiveWorkbook.PivotCaches.Create(SourceType:=xlDatabase, SourceData:=SrcData.Address(False, False, xlA1, xlExternal)) 

' Set the Worksheet object where the Pivot Table will be placed 
Set PvtSht = ThisWorkbook.Worksheets("SUMMARY") 

On Error Resume Next 
'Set the pivot table object 
Set PvtTbl = PvtSht.PivotTables("ZFIGLABACUS") ' check if Pivot Table already created (in past runs of this Macro) 
On Error GoTo 0 
If PvtTbl Is Nothing Then '<-- Pivot Table not created >> create it 
    ' create a new Pivot Table in "SUMMARY" sheet 
    Set PvtTbl = PvtSht.PivotTables.Add(PivotCache:=PvtCache, TableDestination:=PvtSht.Range("I3"), TableName:="ZFIGLABACUS") 
    With PvtTbl 
     With .PivotFields("G/L Account") 
      .Orientation = xlRowField 
      .Position = 1 
     End With 
    End With 

Else ' just refresh the Pivot cache with the updated Range 
    PvtTbl.ChangePivotCache PvtCache 
    PvtTbl.RefreshTable 
End If 

End Sub 
相關問題