VBA-PIVOT表向导方法

时间:2017-04-25 22:04:04

标签: excel-vba pivot-table vba excel

我正在尝试使用以下网站的代码创建一个宏来构建pivottable:

http://msdn.microsoft.com/en-us/library/office/hh243933.aspx

但我一直在

  

错误1004:“无法获得PIVOT TABLE的PIVOTFIELDS属性   CLASS“

有关此问题背后原因的任何建议以及可能的解决方法吗?

这是我的代码

Sub CreatePivot()

' Creates a PivotTable report from the table on Sheet1
' 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("Sheet1").Select
Range("A2").Select

' Create the PivotTable object based on the Employee data on Sheet1.
Set objTable = Sheet1.PivotTableWizard

' Specify row and column fields.
***Set objField = objTable.PivotFields("v1")*** ' <-- This where I get the Error
objField.Orientation = xlColumnField

Set objField = objTable.PivotFields("Temperature")
objField.Orientation = xlRowField

' Specify a data field with its summary
' function and format.
Set objField = objTable.PivotFields("clkui")
objField.Orientation = xlDataField
objField.Function = xlSum
objField.NumberFormat = "$ #,##0"

' Specify a page field.
Set objField = objTable.PivotFields("db")
objField.Orientation = xlPageField

' Preview the new PivotTable report.
ActiveSheet.PrintPreview

' Prompt the user whether to delete the PivotTable.
Application.DisplayAlerts = False
If MsgBox("Delete the PivotTable?", vbYesNo) = vbYes Then
    ActiveSheet.Delete
End If
Application.DisplayAlerts = True

End Sub

enter image description here

1 个答案:

答案 0 :(得分:0)

尝试使用以下代码在“{1}”中创建一个新表格(不确定表格的名称是什么),来自“Sheet1”中的数据:

Sheet1