【问题标题】:Pivot table filtering with 2 cell values具有 2 个单元格值的数据透视表过滤
【发布时间】:2018-08-23 18:41:17
【问题描述】:

我希望在 Excel 2016 中构建一个数据透视表,它会将过滤器s 链接到其他 Excel 单元格,以便它们不是手动调整过滤器,而是链接到单元格值(值更改基于 INDEX-MATCH 公式)。

网上有很多资源,我能够找到一个有效的代码。挑战在于我有 2 个单独的过滤器(我不想合并数据以保持过滤器为 1)。

这很好用,但只适用于一个单元格和一个过滤器:

Private Sub Worksheet_SelectionChange(ByVal Target As Range)
If Intersect(Target, Worksheets(1).Range("I6:I7")) Is Nothing Then Exit Sub

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

'Here you amend to suit your data
Set pt = Worksheets(1).PivotTables("PivotTable1")
Set Field = pt.PivotFields("Brand")
NewCat = Worksheets(1).Range("I6").Value

'Here is the test if the input field exists
test_val = NewCat
For Each pivot_item In pt.PivotFields("Brand").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.CurrentPage = NewCat
pt.RefreshTable
End With
End Sub

还有另一个带有过滤器 "Type" 的 PivotField,我正在尝试将其链接到 Range "H6"。我在此(也作为 WorkSheet 属性)下复制了调整后的代码,其中包含调整后的 Ranges 和 Fields。这些值应该是正确的,因为此代码也可以单独工作。

鉴于不允许我有两个同名代码,我将另一个重命名为 2,我不确定这是否正确。我没有收到任何错误消息,但是第二个代码不起作用。更改单元格“I6”值时我会得到结果,但是对“H6”没有影响。

Private Sub Worksheet_SelectionChange2(ByVal Target As Range)

我怎样才能将这两个过滤器链接到它们各自的单元格(同时)?或者这一切都必须在同一个代码中工作?

最好只通过更改单元格数据使其工作(就像原始代码适用于单个过滤器一样),但是在调整单元格后需要通过按钮启动 VBA 脚本是第二好的选择。

非常感谢!

【问题讨论】:

    标签: vba excel


    【解决方案1】:

    如果您更改检查目标是否与 x 范围相交的方式,则可以在同一组代码中包含大量范围:

    Private Sub Worksheet_SelectionChange(ByVal Target As Range)
    
        If Not Intersect(Target, Worksheets(1).Range("I6:I7")) Is Nothing Then
    
            '<previous code>
    
        ElseIf Not Intersect(Target, Worksheets(1).Range("H6")) Is Nothing Then
    
            '<new code>
    
        End If
    
    End Sub
    

    【讨论】:

      猜你喜欢
      • 2017-07-04
      • 1970-01-01
      • 1970-01-01
      • 2017-04-10
      • 1970-01-01
      • 2017-07-13
      • 2019-01-09
      • 1970-01-01
      • 2017-08-28
      相关资源
      最近更新 更多