gpt4 book ai didi

Excel:根据表格行创建切片器

转载 作者:行者123 更新时间:2023-12-04 21:00:00 26 4
gpt4 key购买 nike

是否可以基于表格标题行创建切片器,而不仅仅是标题列,如下面的模型所示?或者有人可以推荐一种更好的方法来组织这个两轴数据矩阵吗?

我预计该表可能有数百个条目,并且仅比较一小部分 Material 会很有用。

Two-axis data matrix with slicer for both header column and row

最佳答案

这可以通过一些 VBA 代码实现,参见 Hide & Unhide (Filter) Columns with a Slicer or Filter Drop-down我应该说我自己没有对此进行测试,但代码是直截了当且不言自明的。

您需要调整代码,但基本设置是:

  • 一个 Private Sub Worksheet_PivotTableUpdate(ByVal Target As
    PivotTable)
    包含数据透视表的工作表中的宏。

  • ...调用...
  • 一个更长的宏,它遍历列并隐藏那些不符合您的条件的。

  • 他们提供的代码并不是特别复杂(见下文),但我认为对于 VBA 新手来说,这将是具有挑战性的,但并非不可能。
    Private Sub Worksheet_PivotTableUpdate(ByVal Target As PivotTable)
    'Run the filter columns macro when the pivot table or slicer is changed

    Select Case Target.Name
    Case "PivotTable1"
    Call m_FilterCol.Filter_Columns("rngQuarter", "Report", "Report", "PivotTable1", "Quarter")
    End Select

    End Sub

    这是 Filter_Columns 宏代码。
    Sub Filter_Columns(sHeaderRange As String, _
    sReportSheet As String, _
    sPivotSheet As String, _
    sPivotName As String, _
    sPivotField As String _
    )

    Dim c As Range
    Dim rCol As Range
    Dim pi As PivotItem


    'Unhide all columns
    Worksheets(sReportSheet).Range(sHeaderRange).EntireColumn.Hidden = False

    'Loop through each cell in the header range and compare to the selected filter item(s).
    'Hide columns that are not selected/filtered out.

    For Each c In Worksheets(sReportSheet).Range(sHeaderRange).Cells

    'Check if the pivotitem exists
    With Worksheets(sPivotSheet).PivotTables(sPivotName).PivotFields(sPivotField)
    On Error Resume Next
    Set pi = .PivotItems(c.Value)
    On Error GoTo 0
    End With

    'If the pivotitem exists then check if it is visible (filtered)
    If Not pi Is Nothing Then
    If pi.Visible = False Then

    'Add excluded items to the range to be hidden
    If rCol Is Nothing Then
    Set rCol = c
    Else
    Set rCol = Union(rCol, c)
    End If
    End If
    End If

    'Reset the pivotitem
    Set pi = Nothing

    Next c

    'Hide the columns of the range of excluded pivot items
    If Not rCol Is Nothing Then
    rCol.EntireColumn.Hidden = True
    End If

    End Sub

    关于Excel:根据表格行创建切片器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38054933/

    26 4 0
    Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
    广告合作:1813099741@qq.com 6ren.com