>实际上,我正在尝试创建一些VBA代码,该代码将使用数据透视表循环浏览一堆工作表,对数据透视表应用某些条件(即根据变量更改字段/根据单元格值更改过滤器,正如我试图在下面的代码中演示的那样)。这甚至没有接近运行(我是一个尝试更新遗留代码的完全初学者),所以我正在寻找有关如何使用为我想要的结果定义的变量的指针。
我目前的问题是我似乎无法调用数据透视表来开始更改字段等。
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
你有一个循环的For Each MySheet In ActiveWorkbook.Worksheets
,所以当你使用后面的时候With ActiveSheet
它和MySheet
不是同一个工作表,其实你不需要用ActiveSheet
,可以直接使用你命名MyPivot
的PivotTable
对象。
尝试以下代码:
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