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

时间:2016-06-27 13:13:23

标签: excel

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

我希望这个表可能长达数百个条目,并且只需轻松比较一小部分材料就很有用。

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

1 个答案:

答案 0 :(得分:0)

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

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

  1. 工作表中包含数据透视表的Private Sub Worksheet_PivotTableUpdate(ByVal Target As PivotTable)宏。
  2. ......哪个叫...

    1. 一个较长的宏,它遍历列并隐藏那些与您的条件不匹配的宏。
    2. 他们提供的代码并不是特别复杂(见下文),但我认为对于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