如何防止用户在Excel数据透视表中进行多选?

时间:2018-08-02 14:47:50

标签: excel filter pivot-table multi-select slicers

我有一个基于日期的Excel数据透视表。我想强制用户使用1年且只有1年加1年且只有1个季度的报告。无论如何,可以在过滤器或切片器中执行此操作,还是应该在VBA中强行使用它。我对Access和Word中的VBA非常满意,但是在Excel中对VBA的调用还很少。 谢谢!

1 个答案:

答案 0 :(得分:0)

有两种可能的方法。首先,下面是Jerry Sullivan over at the MrExcel forum中的一些代码:

Option Explicit

Private Sub Worksheet_PivotTableUpdate(ByVal Target As PivotTable)
'--when pivot update event triggered, checks whether a specified slicer
'    has more than one item selected.
'  If so, user is warned and optionally the last action can be undone.

 Dim bSlicerIsConnected As Boolean
 Dim pvt As PivotTable
 Dim slc As SlicerCache
 Dim sLastUndoStackItem  As String

 '--modify this to match your slicer's name
 Const sSLICER_NAME As String = "Slicer_Name3"

 sLastUndoStackItem = Application.CommandBars("Standard").FindControl(ID:=128).List(1)

 '--validate event was triggered by slicer or filter, not other pivot operation
 Select Case sLastUndoStackItem
   Case "Slicer Operation", "Filter"
      'continue
   Case Else
      'do nothing and exit
      GoTo ExitProc
 End Select

 '--validate specified slicer exists
 On Error Resume Next
 Set slc = ActiveWorkbook.SlicerCaches(sSLICER_NAME)
 On Error GoTo 0

 If slc Is Nothing Then
   GoTo ExitProc
 End If

 '--validate pvt that triggered event is connected to specified slicer
 For Each pvt In slc.PivotTables
   If pvt.Name = Target.Name Then
      bSlicerIsConnected = True
      Exit For
   End If
 Next pvt

 '--test how many items selected and take action if more than one
 If bSlicerIsConnected Then
   If slc.VisibleSlicerItems.Count > 1 Then
      '--option a: only warn user
      'MsgBox "Only one item may be selected" & vbCr _
      '  & "Please undo last selection."

      '--option b: warn user and undo
     ' MsgBox "Only one item may be selected"
      With Application
         .EnableEvents = False
         .Undo
      End With
   End If
 End If
ExitProc:
   Application.EnableEvents = True
End Sub

如果您不想要VBA,则可以使用s omething like i posted here,方法是创建第二个数据透视表,将感兴趣的字段作为报表筛选器(即“页面字段”)放入其中,然后有效地“整理”两个结果单元格作为一种数据验证下拉列表。您可能需要使用公式来检查是否仅选中了一项(例如,通过检查下拉菜单中是否显示“(全部)”。