我正在尝试使用VBA选择所有以H或N作为其第四个字符的组织。
我尝试修改代码以仅选择H或N并起作用。如果我通过选择不是H或N的所有内容来反转符号,此代码也可以工作。
Sub Select_H_and_N_Organizations_View()
Dim WS As Worksheet
Dim PT As PivotTable
Dim PF As PivotField
Dim PI As PivotItem
Dim blnCheck As Boolean
blnCheck = False
Set WS = ActiveWorkbook.ActiveSheet
If WS.PivotTables.Count > 0 Then
Set PT = WS.PivotTables(1)
PT.ManualUpdate = True
Set PF = PT.PivotFields("Organization")
For Each PI In PF.PivotItems
If Mid(PI.Name, 4, 1) = "H" Or Mid(PI.Name, 4, 1) = "N" Then
blnCheck = True
End If
Next PI
If blnCheck = True Then
Set PF = PT.PivotFields("Organization")
For Each PI In PF.PivotItems
If Mid(PI.Name, 4, 1) = "H" Or Mid(PI.Name, 4, 1) = "N" Then
If PI.Visible = False Then
PI.Visible = True
End If
End If
Next PI
For Each PI In PF.PivotItems
If Mid(PI.Name, 4, 1) <> "H" Or Mid(PI.Name, 4, 1) <> "N" Then
If PI.Visible = True Then
PI.Visible = False ''This is where code breaks
End If
End If
Next PI
Else
MsgBox "There are no H or N Organizations available.", vbOKOnly, "Pivot Tables"
End If
End If
PT.ManualUpdate = False
Set WS = Nothing
Set PT = Nothing
Set PF = Nothing
Set PI = Nothing
End Sub
答案 0 :(得分:0)
您首先检查,是否有任何符合您条件的枢轴项目。正确,因为至少一个枢轴项目必须保持可见。
然后您将每个所需的枢轴项目都切换为可见。
最后,您要隐藏所有不需要的内容。在那里,您只需要将条件从Or
更改为And
,否则您的条件将始终得到满足(所有条件都不可见,并且错误发生在最后一个枢轴项目上,因为必须保持可见):
If Mid(PI.Name, 4, 1) <> "H" And Mid(PI.Name, 4, 1) <> "N" Then