VBA代码运行透视表和更改filter/标签

实际上,我正在尝试创build一些VBA代码,这些代码将通过一系列带有透视表的表循环,将某些条件应用于透视表(即,根据variables更改字段/根据单元格值更改filter,就像我试图在下面的代码中演示)。 这甚至没有接近运行(我是一个完整的初学者试图更新遗留代码),所以我正在寻找指针如何使用为我想要的结果定义的variables。

我目前的问题是,我似乎无法调用数据透视表开始更改字段等。

Option Explicit Dim MySheet As Worksheet Dim MyPivot As PivotTable Dim NewCat As String Sub RefreshPivots() For Each MySheet In ActiveWorkbook.Worksheets For Each MyPivot In MySheet.PivotTables NewCat = Worksheets("WorkingSheet").Range("B44").Value MyPivot.RefreshTable With ActiveSheet .MyPivot.AddDataField .MyPivot.PivotFields ("GuidelinePercent"), "Count of GuidelinePercent", xlCount End With Next MyPivot Next MySheet 

(更多的会进入循环,这只是我遇到的第一个问题)。

我得到: Run-time error '438' Object doesn't support this property or method在线

With ActiveSheet.MyPivot.AddDataField

任何帮助将是伟大的!

编辑;

尝试时

 With ActiveSheet .PivotTables(MyPivot).AddDataField .PivotTables(MyPivot).PivotFields ("GuidelinePercent"), "Count of GuidelinePercent", xlCount End With 

我得到Run-time error'1004': Unable to get the Pivot Tables property of the Worksheet class.MyPivot.AddDataField上的Run-time error'1004': Unable to get the Pivot Tables property of the Worksheet class

你有一个For Each MySheet In ActiveWorkbook.Worksheets的循环For Each MySheet In ActiveWorkbook.Worksheets ,所以当你以后With ActiveSheet它不是MySheet相同的工作表, MySheet你不需要使用ActiveSheet ,你可以直接使用PivotTable对象,你可以命名MyPivot

试试下面的代码:

  With MyPivot .AddDataField .PivotFields("GuidelinePercent"), "Count of GuidelinePercent", xlCount End With 

编辑1

  Dim PvtFld As PivotField With MyPivot On Error Resume Next Set PvtFld = .PivotFields("GuidelinePercent") On Error GoTo 0 If PvtFld Is Nothing Then MsgBox "Error in setting the PivotField" Else .AddDataField PvtFld, "Count of " & PvtFld.Name, xlCount End If End With