【发布时间】:2021-09-02 22:46:44
【问题描述】:
我正在尝试将数据透视表中的切片器与常规表关联起来。所以最后,当我在数据透视表切片器中选择某些内容时,它也应该过滤常规表中的数据。
到目前为止,我按照此解决方案中的说明进行操作:How to link a Table and a Pivot Table using Slicers in Excel?
请在下面找到我在工作簿中使用的确切代码:
Option Explicit
Private Sub Worksheet_PivotTableUpdate(ByVal Target As PivotTable)
Dim sLastUndoStackItem As String
Dim sc As SlicerCache
Dim si As SlicerItem
Dim vItems As Variant
Dim i As Long
Dim lo As ListObject
Dim lc As ListColumn
Dim sTest As String
Const sPivot As String = "pivot1" '<= Change name as appropriate
Const sTable As String = "Table1" '<= Change name as appropriate
If Target.Name = sPivot Then
On Error Resume Next 'in case the undo stack has been wiped or doesn't exist
sLastUndoStackItem = Application.CommandBars(14).FindControl(ID:=128).List(1) 'Standard Commandbar, undo stack
'The above line doesn't seem to work in my version of O365 so we'll use the English language backup
If sLastUndoStackItem = "" Then sLastUndoStackItem = Application.CommandBars("Standard").Controls("&Undo").List(1)
On Error GoTo 0
If sLastUndoStackItem = "Filter" Or sLastUndoStackItem = "Slicer Operation" Then
Set lo = Sheets("Sheet1").Range(sTable).ListObject
For Each sc In ActiveWorkbook.SlicerCaches
On Error Resume Next
sTest = sc.PivotTables(1).Name
On Error GoTo 0
If sTest = sPivot Then
Set lc = lo.ListColumns(sc.SourceName)
If sc.FilterCleared Then
lo.Range.AutoFilter Field:=lc.Index
Else
ReDim vItems(1 To 1)
For Each si In sc.SlicerItems
If si.Selected Then
i = i + 1
ReDim Preserve vItems(1 To i)
vItems(i) = si.Name
End If
Next si
lo.Range.AutoFilter Field:=lc.Index, Criteria1:=vItems, Operator:=xlFilterValues
ReDim vItems(1 To 1)
End If
End If
Next sc
End If
End If
End Sub
使用此代码,我可以从数据透视表切片器中选择一个项目,也可以选择常规表过滤器。这在英语 excel 版本中完美运行,但在其他语言中不起作用,例如波兰语。这意味着当我在波兰语 Excel 版本的数据透视表切片器中选择一个项目时,只有数据透视表过滤器,常规表不受影响。我没有从 VBA 中得到任何错误。我正在寻找一种无论语言版本如何都可以使用的解决方案。
我想问题可能与线路有关:
If sLastUndoStackItem = "" Then sLastUndoStackItem = Application.CommandBars("Standard").Controls("&Undo").List(1)
我使用的是 Excel 2016。
有人可以帮我解决这个问题吗?
【问题讨论】:
-
请显示您在edit提出问题时使用的确切代码。还要解释一下“不起作用” 的含义,因为这不是有用的错误描述。你得到了哪些错误,在哪一行?会发生什么与您预期会发生什么?
-
亲爱的@Pᴇʜ,感谢您的评论。我在我的问题中添加了您需要的信息。
-
尝试用命令栏按钮的波兰语替换
&Undo。如果您不知道确切的名称,您可以编写一个小程序循环通过Application.CommandBars("Standard")和Debug.Print的控件名称:Dim itm: For Each itm In Application.CommandBars("Standard").Controls: Debug.Print itm.Caption: Next itm -
不确定它是否在所有版本的 Excel 上都是静态的,但无论区域设置如何,控件的 Id 参数似乎都保持不变。例如,英语中的
Application.CommandBars("Standard").Controls("&Undo").Id与法语中的Application.CommandBars("Standard").Controls("Ann&uler").Id相同 (128)。 -
你应该可以直接使用FindControl成员函数获得撤消控制:
Application.CommandBars.FindControl(ID:=128).List(1)
标签: excel vba pivot-table