Kumar
Kumar

Reputation: 33

Excel 2010 VBA pivot table creation in a particular worksheet is not working

I was creating a report using VBA in Excel. But when I try to create a pivot table to a particular sheet it is not creating and it is showing a error " Run time error '424' Object required". I posted my code here please tell me what is the problem

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

I need to create pivot table in "reports" work sheet Please help me..

Upvotes: 3

Views: 4298

Answers (1)

Arun
Arun

Reputation: 685

From your question I think you need something like this.

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

This code will create a PivotTable inside report sheet.

I hope this will work for you

Upvotes: 5

Related Questions