自定义右键单击菜单 – OnAction可以直接使用,而不是按下button

我在Excel中创build一个由各种子菜单组成的自定义菜单。 这是为了挑选各种机械物品,并有大约250个可能的结果。

无论如何,我已经build立了菜单并希望它能够在使用菜单时将.Captioninput到单元格中。 我已经把.OnAction放到了相关的button中,但不幸的是.OnAction在打开文件时激活,而不是在button被点击时激活。 就这样,所有250多个这样的元素都快速地进入同一个单元格。

快速编辑 – 重要的是朝向BuildMenus的底部,在那里.OnAction调用函数AddStuff。 我知道这是在Workbook_Activate上运行的,这就是为什么它会立即运行,但我在网上看到的其他地方也是这样。

Private Sub Workbook_Activate() BuildMenus End Sub Private Sub BuildMenus() 'Workbook_SheetBeforeRightClick(ByVal Sh As Object, ByVal Target As Range, Cancel As Boolean) Dim AmountOfCats As Integer Dim ThisIsMyCell As String ThisIsMyCell = ActiveCell.Address 'this is where we would set the amount of categories. At the moment we'll have it as 15 AmountOfCats = 15 Dim cBut As CommandBarControl Dim Cats As CommandBarControl Dim SubCats As CommandBarControl Dim MenuDesc As CommandBarButton On Error Resume Next With Application .CommandBars("Cell").Controls("Pick Machinery/Plant...").Delete End With Set cBut = Application.CommandBars("Cell").Controls.Add(Type:=msoControlPopup, Temporary:=True) cBut.Caption = "Pick Machinery/Plant.." With cBut .Caption = "Pick Machinery/Plant..." .Style = msoButtonCaption End With Dim i As Integer Dim j As Integer Dim k As Integer Dim SC As Integer Dim AmountOfMenus As Integer SC = 1 Dim MD As Integer MD = 1 Dim MyCaption As String For i = 0 To AmountOfCats - 1 Set Cats = cBut.Controls.Add(Type:=msoControlPopup, Temporary:=True) Cats.Caption = Categories(i + 1) Cats.Tag = i + 1 For j = 0 To (SubCatAmounts(i + 1) - 1) Set SubCats = Cats.Controls.Add(Type:=msoControlPopup, Temporary:=True) SubCats.Caption = SubCatArray(SC) SubCats.Tag = j + 1 AmountOfMenus = MenuAmounts(SC) For k = 0 To AmountOfMenus - 1 Set MenuDesc = SubCats.Controls.Add(Type:=msoControlButton) With MenuDesc .Caption = MenuArray(MD) .Tag = MD MyCaption = .Caption .OnAction = AddStuff(MyCaption) End With MD = MD + 1 Next SC = SC + 1 Next Next On Error GoTo 0 End Sub Function AddStuff(Stuff As String) Dim MyCell As String MyCell = ActiveCell.Address ActiveCell.Value = Stuff End Function 

OnAction需要一个string值:相反,您在创build菜单时调用 AddStuff子…

 .OnAction = "AddStuff """ & MyCaption & """" 

是你想要的(假设我的报价是正确的)

我正在与我的AddStuff犯了一个错误 – 我正在调用它作为一个函数,而应该是一个macros(或一个常规的子)。 对Tim Williams的.OnAction代码稍作修改

 MyButton.OnAction = "AddStuff(""" & MyButton.Caption & """)" 

做的伎俩。