在 excel 数据透视过滤器中选择多个项目。但在提及代码中的项目时,我不想具体说明。还有比这更好的方法吗?
Posted
技术标签:
【中文标题】在 excel 数据透视过滤器中选择多个项目。但在提及代码中的项目时,我不想具体说明。还有比这更好的方法吗?【英文标题】:Selecting multiple items in excel pivot filter. But I don't want to be specific while mentioning the items in code. Is there any better way than this? 【发布时间】:2021-07-10 04:06:18 【问题描述】:Sub CreatePivot() 将 PItem 调暗为 PivotItem 将 PTable 调暗为数据透视表
For Each PItem in PTable.PivotFields("Employee_Name").PivotItems
If PItem.Name Like "*XXX*" Or PItem.Name Like "*YYY*" Or PItem.Name Like "*ZZZ*"
PItem.Visible = True
Else
PItem.Visible = False
End If
Next PItem
结束子
【问题讨论】:
【参考方案1】:数据透视表子
以下内容可能会给您一些想法(未经测试)。 调整常量部分中的值。Option Explicit
Sub createPivotTEST()
Const wsName As String = "Sheet1"
Const ptName As String = "Pivottable1"
Const pfName As String = "Employee_Name"
Const CriteriaList As String = "XXX,YYY,ZZZ"
Dim Criteria() As String: Criteria = Split(CriteriaList, ",")
Dim wb As Workbook: Set wb = ThisWorkbook
Dim ws As Worksheet: Set ws = wb.Worksheets(wsName)
Dim pTable As PivotTable: Set pTable = ws.PivotTables(ptName)
Dim pField As PivotField: Set pField = pTable.PivotFields(pfName)
CreatePivot pField, Criteria
End Sub
Sub CreatePivot(ByVal pField As PivotField, ByVal Criteria As Variant)
Dim cLower As Long: cLower = LBound(Criteria)
Dim cUpper As Long: cUpper = UBound(Criteria)
Dim pItem As PivotItem
Dim n As Long
For Each pItem In pField.PivotItems
For n = 0 To cUpper
If pItem.Name Like "*" & Criteria(n) & "*" Then
If Not pItem.Visible Then
pItem.Visible = True
End If
Exit For
End If
Next n
If n > cUpper Then
If pItem.Visible Then
pItem.Visible = False
End If
End If
Next pItem
End Sub
【讨论】:
以上是关于在 excel 数据透视过滤器中选择多个项目。但在提及代码中的项目时,我不想具体说明。还有比这更好的方法吗?的主要内容,如果未能解决你的问题,请参考以下文章