2014-10-22 107 views
3

我在Excel中使用VBA創建報表。但是,當我嘗試創建一個數據透視表到一個特定的工作表時,它並沒有創建,它顯示一個錯誤「運行時錯誤'424'所需對象」。我在這裏發佈我的代碼,請告訴我是什麼問題在特定工作表中創建Excel 2010 VBA數據透視表不起作用

Private Sub CommandButton1_Click() 
    createPivot 
End Sub 
Sub createPivot() 
    ' Creates a PivotTable report from the table on studentmarks 
    ' by using the PivotTableWizard method with the PivotFields 
    ' method to specify the fields in the PivotTable. 
    Dim objTable As PivotTable, objField As PivotField 

    ' Select the sheet and first cell of the table that contains the data. 
    ActiveWorkbook.Sheets("studentmarks").Select 
    Range("A1").Select 


    Set objTable = reports.PivotTableWizard 
    ''''Set objTable = Sheet1.PivotTableWizard // if I give sheet1 instead of reports it is working but every time it is creating new worksheets 
    objTable.ColumnGrand = False 

    ' Specify a page field. 
    Set objField = objTable.PivotFields("subject") 
    objField.Orientation = xlPageField 

    ' Specify row and column fields. 

    Set objField = objTable.PivotFields("name") 
    objField.Orientation = xlRowField 



    Set objField = objTable.PivotFields("subject") 
    objField.Orientation = xlColumnField 

    Set objField = objTable.PivotFields("total") 
    objField.Orientation = xlDataField 



End Sub 

我需要在「報告」工作表 請幫我創建的數據透視表..

回答

3

從你的問題,我認爲你需要像這個。

Dim wsTarget As Worksheet 
Dim rngSource As Range 
Dim pc As PivotCache 
Dim pt As PivotTable 
Dim field As PivotField 

Set rngSource = Sheets("studentmarks").Range("A1").CurrentRegion 
Set wsTarget = Sheets("reports") 

wsTarget.Select 
For Each pt In wsTarget.PivotTables  
     pt.TableRange2.Clear  
Next pt 


Set pc = ThisWorkbook.PivotCaches.Create(xlDatabase, rngSource, xlPivotTableVersion14) 
Set pt = pc.CreatePivotTable(wsTarget.Range("A1"), "PivotTable1", , xlPivotTableVersion14) 

Set field = wsTarget.PivotTables("PivotTable1").PivotFields("subject") 
field.Orientation = xlPageField 

Set field = wsTarget.PivotTables("PivotTable1").PivotFields("subject") 
field.Orientation = xlColumnField 

Set field = wsTarget.PivotTables("PivotTable1").PivotFields("name") 
field.Orientation = xlRowField 

Set field = wsTarget.PivotTables("PivotTable1").PivotFields("total") 
field.Orientation = xlDataField 

此代碼將在報表中創建數據透視表。我希望這會對你有用

相關問題