我有一个名单列表,我需要过滤数据透视表。我使用Case Select来使枢轴项目等于名称可见,而所有其他项目都不可见。我可以制作一次性数组或这15个名称的列表,并在代码中调用列表/数组名称,而不是在多个位置使用15个名称吗?我必须玩一个数据透视表,并多次对这些名称进行排序。
这是我想避免的。它按原样运行,但我试图通过修改来保护自己的头痛。
Set table = Worksheets("Sheet2").PivotTables("PivotTable2")
With table.PivotFields("Assigned to")
For Each PvI In .PivotItems
Select Case PvI.Name
Case "Antone", "Brad", "Cavan", "Chris", "Daneisha", "Edward", "James", "Jonathan", "Joesph", "Karen", "Shaun", "Steve", "Timothy", "Tracey"
PvI.Visible = True
Case Else
PvI.Visible = False
End Select
Next
End With
答案 0 :(得分:0)
试试这个REVERSE
选择案例
Sub Sample()
Dim sNames As String
sNames = "/Antone/Brad/Cavan/Chris/Daneisha/Edward/James/Jonathan/Joesph/Karen/Shaun/Steve/Timothy/Tracey/"
Set Table = Worksheets("Sheet2").PivotTables("PivotTable2")
With Table.PivotFields("Assigned to")
For Each PvI In .PivotItems
Select Case 0 '<~~ Reverse Select case
Case InStr(1, sNames, "/" & PvI.Name & "/", vbTextCompare)
PvI.Visible = False '<~~ This also reverses
Case Else
PvI.Visible = True
End Select
Next
End With
End Sub
以下是查看Reverse Select Case
如何工作的简单方法:)
Sub Sample()
Dim sNames As String, NameToCheck As String
sNames = "/Antone/Brad/Cavan/Chris/Daneisha/Edward/James/Jonathan/Joesph/Karen/Shaun/Steve/Timothy/Tracey/"
NameToCheck = "Antoneeeee"
'NameToCheck = "Daneisha"
Select Case 0
Case InStr(1, sNames, "/" & NameToCheck & "/", vbTextCompare)
MsgBox "Not found"
Case Else
MsgBox " Found"
End Select
End Sub
答案 1 :(得分:0)
当然,它消除了Select Case。我测试了下面的代码减去数据透视表方面。这会将您的名称存储在一个数组中。您可以将数组保留为全局变量或工作簿中的范围(对于后者更改nameArr = ...
行)。代码(UBound(Filter(nameArr, PvI.Name)) > -1)
将通过过滤数组中所需名称并检查结果数组中是否包含任何内容来检查nameArr中是否存在PvI.Name。然后&#34;数组返回的真/假值包含check&#34;被分配到PvI.Visible
。
Dim nameArr As Variant
nameArr = Array("Antone", "Brad", "Cavan", "Chris", "Daneisha", "Edward", "James", "Jonathan", "Joesph", "Karen", "Shaun", "Steve", "Timothy", "Tracey")
Set table = Worksheets("Sheet2").PivotTables("PivotTable2")
With table.PivotFields("Assigned to")
For Each PvI In .PivotItems
PvI.Visible = (UBound(Filter(nameArr, PvI.Name)) > -1)
Next
End With
答案 2 :(得分:0)
在阐述我的评论时,我建议使用表格驱动的方法。
要做的第一件事是将感兴趣的名称放在工作表中,并为该范围指定名称。我打电话给范围&#34; MyNames&#34;在这个例子中。
要做的第二件事是将此功能添加到您的项目中:
Function NameIsInList(LookFor As String) As Boolean
On Error GoTo Err_NameIsInList
NameIsInList = WorksheetFunction.Match(LookFor, Range("MyNames"), 0) > 0
On Error GoTo 0
Exit Function
Err_NameIsInList:
' the name was not found, or a bad parameter was supplied
NameIsInList = False
On Error GoTo 0
End Function
最后,修改您的程序以使用该功能:
Set table = Worksheets("Sheet2").PivotTables("PivotTable2")
With table.PivotFields("Assigned to")
For Each PvI In .PivotItems
PvI.Visible = NameIsInList(PvI.Name)
Next
End With
我在这里拍摄的优势是: