[英]Creating pivot table using vba - run time error
I am trying to create a pivot table using vba. 我正在尝试使用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"
“运行时错误'104'”“对象'_worksheet'的方法'数据透视表'失败”
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. 这是@Rory建议的内容。
You need to use Use ActiveSheet.Pivottablewizard
rather than ws.PivotTableWizard
since there isn't any data on the ws
sheet. 您需要使用Use
ActiveSheet.Pivottablewizard
而不是ws.PivotTableWizard
因为ws
表上没有任何数据。
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: PivotTableWizard方法需要一些参数:
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: 如果仅在es.PivotTableWizard之后打开“(”,则可以看到所有参数,也可以在此处获取它们:
https://msdn.microsoft.com/de-de/library/office/ff839228.aspx https://msdn.microsoft.com/de-de/library/office/ff839228.aspx
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.