I am trying to create a pivot table using vba. Following is the code that i tried:
Sub CreatePivot()
Dim objTable As PivotTable
Dim objField As PivotField
Dim ws As Worksheet
Set ws = Worksheets.Add
Sheets(ws.Name).Name = "Write-Off Pivot"
' Select the sheet and first cell of the table that contains the data.
ActiveWorkbook.Sheets("GEP Write-Offs Rawdata").Select
Range("A1").Select
Set objTable = ws.PivotTableWizard
' Specify row and column fields.
Set objField = objTable.PivotFields("MPG")
objField.Orientation = xlRowField
' Specify a data field with its summary
' function and format.
Set objField = objTable.PivotFields("'A_780610 - Inventory - Obsolescence")
objField.Orientation = xlDataField
objField.Function = xlSum
objField.NumberFormat = "$ #,##0"
End Sub
I am getting this error message. "Run-time error '104'" "method 'pivottables' of object '_worksheet' failed"
The problem seems to be in this line but not able to figure what's causing it.
Set objTable = ws.PivotTableWizard
Your following line needs change.
Set objTable = ws.PivotTableWizard
This should point to data source sheet. So it should be.
Set objTable = Sheets("GEP Write-Offs Rawdata").PivotTableWizard
It will make the pivot table and write in a new added sheet since your command
Set ws = Worksheets.Add
Sheets(ws.Name).Name = "Write-Off Pivot"
is not linked to it.May please modify it suitably.
This is in addition to what @Rory suggested.
You need to use Use ActiveSheet.Pivottablewizard
rather than ws.PivotTableWizard
since there isn't any data on the ws
sheet.
Incidentally, this is unnecessarily convoluted:
Sheets(ws.Name).Name = "Write-Off Pivot"
All you need is:
ws.Name = "Write-Off Pivot"
The methods PivotTableWizard needs some parameters:
Like this:
Set objTable = ws.PivotTableWizard(xlDatabase, ActiveWorkbook.Worksheets("Table8").Range("A1:A5"), ws.Range("A1:A6"))
There are a lot of parameters, for your example i needed the datasource type, the datasource and the datadestination.
You see all parameters if you just open the "(" after es.PivotTableWizard or you can get them here:
https://msdn.microsoft.com/de-de/library/office/ff839228.aspx
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.