有通过每个PivotItems
的无需环路,只需设置pi
对象所需的值,事后验证。
它还看来你没有禁用Application.Events
(通过在过程结束时缺乏Application.EnableEvents = True
),如果是这样的工作表事件再次触发每次PivotField
页面改变时,并且可能是原因的Excel崩溃。
注意,如果PivotField(strField)
没有被设置为PageField
你会得到一个因此"Run-time error 1004: Unable to get the PageFields property of the PivotTable class"
的PivotField(strField)
需要验证为PageField
(请参见下面的代码)。
假设程序是Worksheet Change Event
试试这个(参见代码中的注释):
Private Sub Worksheet_Change(ByVal Target As Range)
Dim pt As PivotTable
Dim pf As PivotField
Dim pi As PivotItem
Dim strField As String
strField = "Cslts"
Application.EnableEvents = False 'This avoids the Worksheet event from restarting again every time the PivotTable page is changed.
Application.ScreenUpdating = False
If Target.Address = "$H$1" Then
For Each pt In Target.Worksheet.PivotTables
Rem Set PageField
Set pf = Nothing
On Error Resume Next
Set pf = pt.PageFields(strField)
On Error GoTo 0
Rem Validate PageField
If Not (pf Is Nothing) Then
With pf
.EnableMultiplePageItems = False
Rem Set PageField Item
Set pi = Nothing 'Initialize Item object
On Error Resume Next 'This will avoid an error if the item is not present
Set pi = .PivotItems(Target.Value2) 'No need to loop through the items just set the required item
On Error GoTo 0 'Clears the Error Object
Rem Validate & Set PageField Item
If Not (pi Is Nothing) Then
.CurrentPage = Target.Value2
Else
.CurrentPage = "(blank)"
End If: End With: End If: Next: End If
Application.EnableEvents = True
Application.ScreenUpdating = True
End Sub
此外,建议刷新PivotTables
,以确保您从源数据的最新更新工作,还要注意PivotItem
属性Value
和SourceName
可能具有的不同值。
推荐阅读以下网页获得的资源有了更深的了解使用:
On Error Statement,
PivotCache Object (Excel),PivotFields Object (Excel),PivotItems Object (Excel)
来源
2017-03-28 17:27:10
EEM
调试时,你应该总是避免'上的错误恢复下一页'因为它会掩盖你正在寻找的错误。同样,如果您正在寻找代码处理的特定错误,它应该只在您的代码中。 –
如果'pi.Value = Target.Value',则可以通过将布尔值设置为true,然后只设置'.CurrentPage =“(空白)”'如果未设置该布尔值,则可以使If块更高效。现在,您可以在*每个循环中设置.currentpage的值,直到“pi = target”。我的改变将有助于表现(可能有很大的帮助)。 –
嗨斯科特,谢谢你的建议,但你能澄清,因为我不确定如何改变这个问题吗? – dlan