我正在尝试使用excel vba创建的数据透视表创建前10个值,但似乎我收到了错误
运行时错误'1004':
应用程序定义或对象定义错误
这是代码,我通过互联网搜索后似乎无法找到问题
Sub PivotGenerate()
'declaration
Dim sht As Worksheet
Dim pvt As PivotTable
Dim pvtFld As PivotField
Dim pvtCache As PivotCache
Dim StartPvt As String
Dim SrcData As String
Dim RangeInput As Range
'Input value
Set RangeInput = Application.InputBox(Prompt:= _
"Please Select Name range", _
Title:="InputBox Method", Type:=8)
'Stop Updating
Application.ScreenUpdating = False
'data range for pivot
SrcData = ActiveSheet.Name & "!" & RangeInput.Address(ReferenceStyle:=xlR1C1)
'error handling for new worksheet
Application.DisplayAlerts = False
On Error Resume Next
ThisWorkbook.Sheets("PivotTable").Delete
On Error GoTo 0
Application.DisplayAlerts = True
'create new worksheet
Set sht = Worksheets.Add(After:=Sheets(Worksheets.Count))
sht.Name = "PivotTable"
'Pivot Table location
StartPvt = sht.Name & "!" & sht.Range("A3").Address(ReferenceStyle:=xlR1C1)
'Create Pivot Cache from Source Data
Set pvtCache = ActiveWorkbook.PivotCaches.Create( _
SourceType:=xlDatabase, _
SourceData:=SrcData)
'Create Pivot table from Pivot Cache
Set pvt = pvtCache.CreatePivotTable(TableDestination:=StartPvt, TableName:="Top 10 Commitment Value")
'Set active
Set pvt = ActiveSheet.PivotTables("Top 10 Commitment Value")
'Classic View
pvt.InGridDropZones = True
pvt.RowAxisLayout xlTabularRow
'Remove Subtotal
With pvt
For Each pvtFld In .PivotFields
pvtFld.Subtotals(1) = False
Next pvtFld
End With
'Row Labels
pvt.PivotFields("CUST Name").Orientation = xlRowField
pvt.PivotFields("CUST Name").Position = 1
'Data Value
pvt.AddDataField pvt.PivotFields("Commitment RM"), "Sum of Commitment RM", xlSum
pvt.AddDataField pvt.PivotFields("OS BALANCE RM (On BS)"), "Sum of OS BALANCE RM (On BS)", xlSum
pvt.PivotFields("CUST Name").AutoShow Type:=xlAutomatic, Range:=xlTop, Count:=5, Field:="Sum of Commitment RM"
'Activate Updating
Application.ScreenUpdating = True
End Sub
调试在代码中突出显示了这一行
pvt.PivotFields(“CUST Name”)。AutoShow Type:= xlAutomatic,Range:= xlTop,Count:= 5,Field:=“Commitment of Commitment”
可以生成数据透视表,但前10行产生了错误
答案 0 :(得分:1)
感谢 Doug Glancy 的帮助,这是我从Macro Recorder获得的
ActiveSheet.PivotTables("PivotTableTop10").PivotFields("CUST NAME"). _ PivotFilters.Add2 Type:=xlTopCount, DataField:=ActiveSheet.PivotTables( _ "PivotTableTop10").PivotFields("Sum of Commitment RM"), Value1:=10