【问题标题】:Error 1004 vba pivot filter contains value错误 1004 vba 数据透视过滤器包含值
【发布时间】:2019-03-16 01:12:21
【问题描述】:

此代码最初运行良好。 但是经过几次测试后出现错误1004。 这一行的代码中断

Set Field = pt.PivotFields("Rep Order#")

我检查了数据透视表中的字段名称。完全一样。

谁能帮忙看看?

Private Sub Workbook_SheetChange(ByVal Sh As Object, ByVal Target As Range)

    'Set the Variables to be used
    Dim pt As PivotTable
    Dim pt2 As PivotTable
    Dim Field As PivotField
    Dim Field2 As PivotField
    Dim pivot_item As PivotItem
    Dim pivot_item2 As PivotItem
    Dim NewCat As String
    Dim test_val As String

    'Here you amend to suit your data
    Set pt = Worksheets("Backlog Analysis 2").PivotTables("PivotTable2")
    Set pt2 = Worksheets("Backlog Analysis 2").PivotTables("PivotTable1")
    Set Field = pt.PivotFields("Rep Order#")
    Set Field2 = pt2.PivotFields("Rep Order#")

    NewCat = Worksheets("Backlog Analysis 2").Range("L11").Value

    'Here is the test if the input field exists
    test_val = NewCat
    For Each pivot_item In pt.PivotFields("Rep Order#").PivotItems
        If pivot_item.Name = test_val Then
            Exit For
        End If
    Next pivot_item
    On Error Resume Next

    'This updates and refreshes the PIVOT table
    With pt
        Field.ClearAllFilters
        Field.PivotFilters.Add2 Type:=xlCaptionContains, Value1:=NewCat
        pt.RefreshTable
    End With

    With pt2
        Field2.ClearAllFilters
        Field2.PivotFilters.Add2 Type:=xlCaptionContains, Value1:=NewCat
        pt.RefreshTable
    End With

End Sub

【问题讨论】:

    标签: vba filter runtime-error pivot-table


    【解决方案1】:

    如果代码最初工作然后停止工作,我的第一个猜测是关闭事件或限制代码仅在特定范围更改时运行。您的代码现在每次在工作簿中发生任何更改时都会运行(包括您的代码更改数据透视表时)。

    尝试在代码开头添加:

    Application.EnableEvents = False
    

    最后是这个:

    Application.EnableEvents = True
    

    另外,您似乎真的只希望在 Range("L11") 更改时运行它。因此,您可以在顶部添加一个条件:

    If Target.Address = "$L$11" And Sh.Name = "Backlog Analysis 2" Then
        'Run Your Code
    End If
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-07-02
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多