首页 > 解决方案 > 错误 1004 vba 数据透视过滤器包含值

问题描述

这段代码最初运行良好。但是经过几次测试后出现错误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

标签: vbafilterruntime-errorpivot-table

解决方案


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

尝试在代码开头添加:

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

推荐阅读