为什么我不能使用VBA在Excel 2013中编辑命令行控件?

我正在试图通过VBA来为数据透视表做我自己的钻取操作。 该操作将从其他操作的数据透视表的上下文菜单中调用。 我想把我的button下数据透视表上下文菜单命令栏的附加操作控制。 重点是默认附加操作已经包含(没有操作定义)项目。 所以,我想删除这个(没有行动定义)后添加我的button,但没有任何工作。 我甚至无法更改(无操作定义)控件的任何属性,如Caption,Visible等。可能是什么原因,以及解决方法是什么? 这里是我的代码到目前为止(例如,你可以把它放在Workbook_SheetBeforeRightClick,然后testing该工作簿中的任何数据透视表):

Dim PCell As PivotCell Dim PComBar As CommandBar Dim PControl As CommandBarControl Dim DControl As CommandBarControl Dim BControl As CommandBarControl Dim IsFromPivotTable As Boolean IsFromPivotTable = False On Error GoTo NotFromPivot Set PCell = Target.PivotCell IsFromPivotTable = True NotFromPivot: On Error GoTo 0 If IsFromPivotTable Then Set PComBar = Application.CommandBars("PivotTable Context Menu") Set PControl = PComBar.Controls("Additional Actions") On Error Resume Next With PControl Call .Controls("My Drillthrough Action").Delete .Enabled = True End With On Error GoTo 0 Set DControl = PControl.Controls.Add(Type:=msoControlButton, Temporary:=True, Before:=1) With DControl .Style = msoButtonIconAndCaption .Caption = "My Drillthrough Action" .FaceId = 786 End With On Error Resume Next Set BControl = PControl.Controls("(No Actions Defined)") With BControl 'This does not work and throws error if do not suppress with On Error .Enabled = True .Visible = False .Caption = "Hello there" End With On Error GoTo 0 End If 

所以,最后一节BControl … End With完全不起作用,并引发错误“自动化错误”。 我可以成功编辑其他操作本身,如启用它,但我想摆脱(无操作定义)控制,或用我自己的replace。 请注意,这个Call .Controls(“(No Actions Defined)”)。Delete也不起作用。 我怎样才能做到这一点? 我试图谷歌的问题,但没有运气…

我怀疑你不能添加到该菜单。 但是,您可以将其添加到上下文菜单本身:

 Sub test() Dim PCell As PivotCell Dim PComBar As CommandBar Dim DControl As CommandBarControl Dim target As Excel.Range Set target = ActiveCell On Error Resume Next Set PCell = ActiveCell.PivotCell On Error GoTo 0 If Not PCell Is Nothing Then Set PComBar = Application.CommandBars("PivotTable Context Menu") Set DControl = PComBar.Controls.Add(Type:=msoControlButton, Temporary:=True, Before:=1) With DControl .Style = msoButtonIconAndCaption .Caption = "My Drillthrough Action" .FaceId = 786 End With End If End Sub