我正在寻找一种基于机器类型(我拖到我的数据透视表的过滤器框的字段)过滤数据透视表的方法。我以前使用过下面的公式,并且一直有效,但是,我收到一条错误消息,说“ 1004:无法获取数据透视表类的PivotFields属性。
任何帮助将不胜感激,已经在这个项目上工作了很长时间,这是我需要完成的最后一步。 (FYI单元格A1具有我要过滤的机器名称)
Sub FilterbyMachine()
Dim pt As PivotTable
Set pt = Sheets("Pivottables").PivotTables("MachineStats")
Dim pf As PivotField
Set pf = pt.PivotFields("Machine")
pf.ClearAllFilters
'slow iterates all items and sets Visible (manual filter)
Dim pi As PivotItem
For Each pi In pf.PivotItems
pi.Visible = (pi.Name = Range("a1"))
Next
'fast way sets a label filter
pf.PivotFilters.Add2 Type:=xlCaptionEquals, Value1:=Range("a1")
End Sub
答案 0 :(得分:0)
您在此行遇到错误吗?:
Set pf = pt.PivotFields("Machine")
我认为可能是由于该名称可能没有数据透视字段。 Like here.
尝试在该行之前添加此名称,以检查其中有什么名称:
For Each pf In pt.PivotFields
Debug.Print (pf.Name)
Next pf
编辑其他选项: 它可能与数据透视缓存有关。您可以尝试在同一位置调用子from here(如下)。
Sub RefreshAllPivotCaches()
' Developed by Contextures Inc.
' www.contextures.com
Dim wb As Workbook
Dim lPCs As Long
Dim lPC As Long
Dim lProb As Long
Set wb = Application.ThisWorkbook
lPCs = wb.PivotCaches.Count
For lPC = 1 To lPCs
wb.PivotCaches(lPC).Refresh
If Err.Number <> 0 Then
MsgBox "Could not refresh pivot cache " & lPC _
& vbCrLf _
& "Error: " _
& vbCrLf _
& Err.Description
Err.Clear
lProb = lProb + 1
End If
Next lPC
MsgBox "Refresh is complete. " _
& vbCrLf _
& "Pivot Cache Count: " & lPCs _
& vbCrLf _
& "Failed refreshes: " & lProb
End Sub
可能没有必要保留它。尝试单独运行一次。然后是你的代码。如果这样很好,您可能希望在设置的pf行周围进行错误处理方面的调用。万一再次发生。像这样:
Setpf:
Dim CachesCleared as Boolean
On Error Goto ClearPivotCache
Set pf = pt.PivotFields("Machine")
Goto FieldsAreGood ' no need to clear if it's working
ClearPivotCache:
On Error Goto 0 ' reset error handling
If not CachesCleared Then ' only try clearing once, no infinite loops
Call RefreshAllPivotCaches
CachesCleared = True
Goto SetPF
Endif
FieldsAreGood:
On Error Goto 0 ' reset error handling
' The rest of your code