我有一个基于日期的 Excel 数据透视表。我想强制用户使用 1 年且仅 1 年加 1 且仅 1 个季度进行报告。无论如何要在过滤器或切片器中执行此操作,还是应该在 VBA 中强制执行此操作。我对 Access 和 Word 中的 VBA 非常满意,但在 Excel 中对 VBA 的调用并不多。谢谢!
问问题
3928 次
1 回答
0
有几种可能的方法。首先,这是来自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,那么您可以使用我在此处发布的内容,通过创建第二个数据透视表,将感兴趣的字段作为报告过滤器(即页面字段)放入其中,然后有效地“修饰”两个结果单元格作为一种数据验证下拉菜单。您需要使用公式来检查是否只选择了一项(即通过检查下拉菜单是否显示“(全部)”。
于 2018-08-02T20:20:02.317 回答