【问题标题】:Unable to get the PivotFields property of the PivotTable Class - Not sure what I am doing incorrectly无法获取数据透视表类的 PivotFields 属性 - 不确定我做错了什么
【发布时间】:2020-03-10 17:49:11
【问题描述】:

我正在寻找一种方法来根据机器类型(我将一个字段拖到我的数据透视表的过滤器框)过滤我的数据透视表。我之前使用过下面的公式,它已经奏效了,但是,我收到一条错误消息,提示“1004:无法获取数据透视表类的数据透视字段。

任何帮助都将不胜感激,我已经在这个项目上工作了很长时间,这是我需要完成的最后一步。 (仅供参考,单元格 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

【问题讨论】:

  • 这对你的问题没有帮助,但是在循环之前pt.ManualUpdate = True然后设置为False肯定会提高速度。

标签: excel vba filter pivot


【解决方案1】:

你在这行得到错误?:

 Set pf = pt.PivotFields("Machine")

我认为可能没有该名称的 pivotField。 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

可能没有必要保留它。尝试单独运行一次。然后你的代码。如果这很好,您可能希望在 set 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

如果它确实有效并且你以某种方式包含它,你可能想要注释掉,或者换成 Debug.Prints,MsgBoxes。

【讨论】:

  • 我在 "Dim pf As PivotField" 和 Set pf = pt.PivotFields("Machine")" 之间添加了上述行(复制和粘贴)但是我仍然收到错误消息对于 Set pf 行。Machine 字段位于我的数据透视表中(我可以将其设为列、过滤器等 - 目前我将它放在过滤器下)。
猜你喜欢
  • 2013-06-30
  • 2016-12-21
  • 1970-01-01
  • 1970-01-01
  • 2013-09-21
  • 2019-12-31
  • 1970-01-01
  • 2015-12-30
  • 2021-03-25
相关资源
最近更新 更多