Kum*_*mar 3 excel vba excel-vba
我在Excel中使用VBA创建报告。但是,当我尝试创建到特定工作表的数据透视表时,它没有创建,并且显示错误“运行时错误'424'对象必需”。我在这里发布了代码,请告诉我是什么问题
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
Run Code Online (Sandbox Code Playgroud)
我需要在“报告”工作表中创建数据透视表。请帮助我。
根据您的问题,我认为您需要这样的东西。
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
Run Code Online (Sandbox Code Playgroud)
此代码将在报表中创建一个数据透视表。
我希望这对你有用