Excel 自定义右键单击菜单-OnAction直接工作,而不是按按钮
我正在Excel中创建一个自定义菜单,它由多个子菜单组成。它用于挑选各种机械设备,大约有250种可能的结果 在任何情况下,我已经构建了菜单,并希望它在使用菜单时将.Caption输入到单元格中。我已将.OnAction放入相关按钮中,但不幸的是,.OnAction在打开文件时激活,而不是在单击按钮时激活。因此,所有250多个标题都会快速连续地输入到同一单元格中 快速编辑-重要的一点是在构建菜单的底部,在那里.OnAction调用函数AddStuff。我知道这是在工作簿上运行的,这就是为什么它会直接运行,但我在网上看到的其他地方都是这样Excel 自定义右键单击菜单-OnAction直接工作,而不是按按钮,excel,vba,menu,right-click,Excel,Vba,Menu,Right Click,我正在Excel中创建一个自定义菜单,它由多个子菜单组成。它用于挑选各种机械设备,大约有250种可能的结果 在任何情况下,我已经构建了菜单,并希望它在使用菜单时将.Caption输入到单元格中。我已将.OnAction放入相关按钮中,但不幸的是,.OnAction在打开文件时激活,而不是在单击按钮时激活。因此,所有250多个标题都会快速连续地输入到同一单元格中 快速编辑-重要的一点是在构建菜单的底部,在那里.OnAction调用函数AddStuff。我知道这是在工作簿上运行的,这就是为什么它会直
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需要一个字符串值:而是在创建菜单时调用AddStuff子项
.OnAction = "AddStuff """ & MyCaption & """"
是您想要的(假设我的引号正确)我的
AddStuff
犯了一个错误-我将它作为一个函数调用,而它本应是一个宏(或常规子函数)。对Tim Williams的.OnAction代码稍作修改
MyButton.OnAction = "AddStuff(""" & MyButton.Caption & """)"
成功了。这个.OnAction对我来说很好。问题是,一旦文件打开,所有的.OnActions都会立即执行。我希望它们只在单击时执行。那么这与我的回答(您不接受)有什么不同呢?