excel - 如何防止 Excel 数据透视表中的用户多选?
问题描述
我有一个基于日期的 Excel 数据透视表。我想强制用户使用 1 年且仅 1 年加 1 且仅 1 个季度进行报告。无论如何要在过滤器或切片器中执行此操作,还是应该在 VBA 中强制执行此操作。我对 Access 和 Word 中的 VBA 非常满意,但在 Excel 中对 VBA 的调用并不多。谢谢!
解决方案
有几种可能的方法。首先,这是来自MrExcel 论坛的 Jerry Sullivan的一些代码:
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,那么您可以使用我在此处发布的内容,通过创建第二个数据透视表,将感兴趣的字段作为报告过滤器(即页面字段)放入其中,然后有效地“修饰”两个结果单元格作为一种数据验证下拉菜单。您需要使用公式来检查是否只选择了一项(即通过检查下拉菜单是否显示“(全部)”。
推荐阅读
- android - 如何使用 Dpad/Game Controller 选择并单击 Android ViewPager2 的子视图
- r - R mschart 折线图的虚线
- python - 根据子类对象(__str__)更改没有字段的超类的表示
- r - 在直方图上显示 x 轴标签以使用 R 进行区间切割
- html - 如何使用弹簧从表单中获取未编辑的对象
- c# - 未找到 EffectDirectPropertyChangeDefinition.cs 进行发布构建 UWP
- wordpress - 如果图像丢失,如何添加默认 og:image?
- model - Faster R-CNN ResNet101 V1 800x1333 Ignore pre-trained weight
- c++ - 数组到指针的转换 + rvalue-ref:重载分辨率差异 GCC vs clang
- javascript - 当它已经解决时,同步运行承诺的最佳方式是什么?