vba - 错误 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
解决方案
如果代码最初工作然后停止工作,我的第一个猜测是关闭事件或限制代码仅在特定范围更改时运行。现在,每当工作簿中发生任何更改(包括您的代码更改数据透视表时)时,我们都会运行您的代码。
尝试在代码开头添加:
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
推荐阅读
- ubuntu - tesseract 4 为什么我的训练数据没有编译
- javascript - 有没有办法在不使用道具的情况下更新反应组件?
- spring-boot - 当您已经有一个应用程序端池时,您还需要 AWS RDS 代理吗?
- r - 将许多数据帧与两个相等的列合并,但 R 中的一个特定列
- python - 如何组织一个循环遍历元素列表的 JavaScript 网站 Scrapy 爬虫
- elixir - 如何使用一个字段的转换值作为 Ecto 中另一个字段的默认值
- sql - Visual Studio 2019 - SQL dacpac - 违反 UNIQUE KEY 约束 ....重复键值为 (
) - c++ - 如何使用并行性来提高我的代码的性能?(尝试了一些东西)
- python - 返回值为真的熊猫系列
- azure - CosmosDb 复杂排序