【发布时间】: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