错误1004 vba枢轴过滤器包含值

时间:2018-10-11 03:42:12

标签: vba filter runtime-error pivot-table

此代码最初运行良好。 但是经过几次测试,错误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

1 个答案:

答案 0 :(得分:0)

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

尝试在代码的开头添加此代码:

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