vba 如何将菜单项添加到默认的右键单击上下文菜单

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/770425/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-08 09:44:30  来源:igfitidea点击:

How to add a menu item to the default right click context menu

ms-accessvbamenucontrolspopup

提问by Curtis Inderwiesche

The goal is to create menus which can be utilized with certain controls on an MS Access form and to be able to right click on a that control, for example on a listbox and a relevant context specific menu popup with options, which if clicked, would trigger a predefined subroutine or function.

目标是创建可以与 MS Access 表单上的某些控件一起使用的菜单,并能够右键单击该控件,例如在列表框和带有选项的相关上下文特定菜单弹出窗口上,如果单击,将触发预定义的子程序或函数。

What is the best method to accomplish this programmatically?

以编程方式完成此任务的最佳方法是什么?

I am using MS Access 2003 and would like to do this using VBA.

我正在使用 MS Access 2003 并希望使用 VBA 来执行此操作。

回答by Curtis Inderwiesche

First create an _MouseUpevent to execute on the respective control looking to see if the right mouse button was clicked and if so, call the .ShowPopupmethod.

首先创建一个_MouseUp在相应控件上执行的事件,以查看是否单击了鼠标右键,如果是,则调用该.ShowPopup方法。

Of course this assumes the

当然,这是假设

Private Sub MyListControlName_MouseUp(ByVal Button As Integer, _
                                      ByVal Shift As Integer, _
                                      ByVal X As Long, ByVal Y As Long)

  ' Call the SetUpContextMenu function to ensure it is setup with most current context
  ' Note: This really only needs to be setup once for this example since nothing is 
  ' changed contextually here, but it could be further expanded to accomplish this
  SetUpContextMenu  
  ' See if the right mouse button was clicked
  If Button = acRightButton Then
    CommandBars("MyListControlContextMenu").ShowPopup
  End If
End Sub

Since at this point the Command Bar MyListControlContextMenuis undefined, I define the Menu in a separate module as follows:

由于此时命令栏MyListControlContextMenu未定义,我在单独的模块中定义菜单如下:

Public Sub SetUpContextMenu()
  ' Note: This requires a reference to Microsoft Office Object Library
    Dim combo As CommandBarComboBox

    ' Since it may have been defined in the past, it should be deleted, 
    ' or if it has not been defined in the past, the error should be ignored

    On Error Resume Next 
    CommandBars("MyListControlContextMenu").Delete
    On Error GoTo 0

    ' Make this menu a popup menu 
    With CommandBars.Add(Name:="MyListControlContextMenu", Position:=msoBarPopup)

    ' Provide the user the ability to input text using the msoControlEdit type
    Set combo = .Controls.Add(Type:=msoControlEdit)
        combo.Caption = "Lookup Text:"           ' Add a label the user will see
        combo.OnAction = "getText"               ' Add the name of a function to call

    ' Provide the user the ability to click a menu option to execute a function    
    Set combo = .Controls.Add(Type:=msoControlButton)
        combo.BeginGroup = True                  ' Add a line to separate above group
        combo.Caption = "Lookup Details"         ' Add label the user will see
        combo.OnAction = "LookupDetailsFunction" ' Add the name of a function to call

    ' Provide the user the ability to click a menu option to execute a function        
    Set combo = .Controls.Add(Type:=msoControlButton)
        combo.Caption = "Delete Record"          ' Add a label the user will see
        combo.OnAction = "DeleteRecordFunction"  ' Add the name of the function to call

  End With

End Sub 

Since three function have been referenced, we can move on to define these as follows-

由于已经引用了三个函数,我们可以继续定义它们如下:

getText: Note, this option requires a reference to both the name of the Command Bar menu nameas well as the name of the control caption.

getText:请注意,此选项需要引用命令栏菜单名称的名称以及控件标题的名称。

Public Function getText() As String

   getText = CommandBars("MyListControlContextMenu").Controls("Lookup Text:").Text

   ' You could optionally do something with this text here, 
   ' such as pass it into another function ...
   MsgBox "You typed the following text into the menu: " & getText

End Function

LookupDetailsFunction: For this example, I will create a shell function and return the text "Hello World!".

LookupDetailsFunction:对于这个例子,我将创建一个 shell 函数并返回文本“Hello World!”。

Public Function LookupDetailsFunction() As String

   LookupDetailsFunction = "Hello World!"

   MsgBox LookupDetailsFunction, vbInformation, "Notice!"

End Function

DeleteRecordFunction: For this example, I will ensure the control is still valid by checking it against null, and if still valid, will execute a query to remove the record from a table.

DeleteRecordFunction:对于这个例子,我将通过检查它是否为空来确保控件仍然有效,如果仍然有效,将执行查询以从表中删除记录。

Public Function DeleteRecordFunction() As String

   If Not IsNull(Forms!MyFormName.Controls("MyListControlName").Column(0)) Then
     Currentdb.Execute _
      "DELETE * FROM [MyTableName] " & _
      "WHERE MyKey = " & Forms!MyFormName.Controls("MyListControlName").Column(0) & ";"
     MsgBox "Record Deleted", vbInformation, "Notice!"
   End If

End Function

Note: For LookupDetailsFunction, DeleteRecordFunctionand getTextfunctions, these must be within a public scope to work correctly.

注意:对于LookupDetailsFunction,DeleteRecordFunctiongetText函数,这些必须在公共范围内才能正常工作。

Finally, the last step is to test the menu. To do this, open the form, right click on the list control and select one of the options from the popup menu.

最后,最后一步是测试菜单。为此,打开表单,右键单击列表控件并从弹出菜单中选择一个选项。

Optionally button.FaceIDcan be utilized to indicate a known office icon to associate with each instance of the menu popup control.

可选地,button.FaceID可用于指示已知的办公室图标以与菜单弹出控件的每个实例相关联。

I found Pillai Shyam's workon creating a FaceID Browser Add-In to be very helpful.

我发现Pillai Shyam在创建 FaceID 浏览器插件方面的工作非常有帮助。

References: MicrosoftFaceID

参考资料: Microsoft FaceID

回答by David-W-Fenton

In order to replace the default shortcut menu with a menu that includes the default actions plus your custom actions, you have to create a custom shortcut menu that includes the default actions. There is no way to extend the default shortcut menu.

为了用包含默认操作和自定义操作的菜单替换默认快捷菜单,您必须创建一个包含默认操作的自定义快捷菜单。无法扩展默认快捷菜单。

Shortcut menus in Access 2003 and before are a special kind of toolbar. You create them the same way (more or less) that you create a custom toolbar. The UI is kind of weird, though, as there's a special place where you create them.

Access 2003 及之前版本中的快捷菜单是一种特殊的工具栏。您创建它们的方式(或多或少)与创建自定义工具栏的方式相同。不过,用户界面有点奇怪,因为有一个特殊的地方可以创建它们。

To get started, right click the toolbar in your front-end Access MDB. Choose CUSTOMIZE. In the list of Toolbars, check off SHORTCUT MENUS. This will give you a list of all the built-in shortcut menus, except that they don't actually end up looking like that in real use. For instance, if right click on a form, you get this shortcut menu:

首先,右键单击前端 Access MDB 中的工具栏。选择自定义。在工具栏列表中,勾选快捷菜单。这将为您提供所有内置快捷菜单的列表,除了它们在实际使用中实际上并不像那样。例如,如果右键单击表单,您将获得以下快捷菜单:

Form Design
Datasheet View
PivotTable View
PivotChart View
Filter By Form
Apply Filter/Sort
Remove Filter/Sort
Cut
Copy
Paste
Properties

Now, where is this menu on the shortcut menu? Well, this one happens to be the FORM VIEW TITLE BAR menu, even though it pops up any time you click anywhere other than on a control on the form. So, if that's the menu you want to alter, you could edit it by adding menu items to it (a drag-and-drop operation).

现在,这个菜单在快捷菜单上的什么位置?好吧,这恰好是 FORM VIEW TITLE BAR 菜单,即使您在单击窗体上的控件以外的任何位置时都会弹出它。因此,如果这是您想要更改的菜单,您可以通过向其添加菜单项(拖放操作)来对其进行编辑。

I think it's actually better (as I said above) to create a custom shortcut menu that replicates the built-in menu and add your enhancements because this allows you to retain the Access default shortcut menu while also having your customized version of it for use when you want it. In that case, you'd need to start a new shortcut menu, and here's where the UI is weird:

我认为创建一个复制内置菜单并添加增强功能的自定义快捷菜单实际上更好(正如我上面所说的),因为这使您可以保留 Access 默认快捷菜单,同时还可以在以下情况下使用它的自定义版本你想要它。在这种情况下,您需要启动一个新的快捷菜单,这就是 UI 奇怪的地方:

You click on the last choice on the shortcut menu, CUSTOM. You see it drops down a placeholder. You can't drag/drop to it. Instead, you have to click NEW in the main toolbar editing window and create a new shortcut toolbar (give it the name you want your custom shortcut menu to have). Your new toolbar now shows up in the list of toolbars. Highlight it and click PROPERTIES, and change the type to POPUP. This will give you an informative warning that this alteration changes it from a toolbar to a shortcut menu. You can then close your toolbar/shortcut menu's properties sheet, and now if you check off SHORTCUT MENUS again and look at the CUSTOM menu, you'll see your newly-created menu. Now you can drag and drop the menu items for the built-in menu to your new menu -- but don't drop them on the menu itself, but on the placeholder in the flyout from the > to the right of the menu name.

单击快捷菜单上的最后一个选项 CUSTOM。你会看到它下降了一个占位符。你不能拖/放它。相反,您必须在主工具栏编辑窗口中单击 NEW 并创建一个新的快捷工具栏(为其指定您希望自定义快捷菜单的名称)。您的新工具栏现在显示在工具栏列表中。突出显示它并单击属性,并将类型更改为 POPUP。这将向您提供信息警告,说明此更改将其从工具栏更改为快捷菜单。然后您可以关闭工具栏/快捷菜单的属性表,现在如果您再次选中快捷菜单并查看自定义菜单,您将看到新创建的菜单。现在您可以将内置菜单的菜单项拖放到新菜单中——但不要将它们放在菜单本身上,

You can then drag and drop any options you want from any menus or toolbars to your custom menu.

然后,您可以将所需的任何选项从任何菜单或工具栏拖放到自定义菜单中。

I assume you know how to use the shortcut menu, as it's part of the properties sheet of all form objects.

我假设您知道如何使用快捷菜单,因为它是所有表单对象的属性表的一部分。

UPDATE 2009/05/21: The official Access 2007 blog just posted an article on doing this programmaticallyin Access 2007. Because of the ribbon interface, there are going to be differences, but some things will be the same.

2009 年 5 月 21 日更新:Access 2007 官方博客刚刚发布了一篇关于在 Access 2007 中以编程方式执行此操作文章。由于功能区界面的原因,会有一些差异,但有些事情是相同的。

回答by THEn

Try This

尝试这个

Sub Add2Menu()
  Set newItem = CommandBars("Form View Popup").Controls.Add(Type:=1)
  With newItem
    .BeginGroup = True
    .Caption = "Make Report"
    .FaceID = 0
    .OnAction = "qtrReport"
  End With
End Sub

As you can see it will add item in "Form View Popup" Command Bar and when this item is clicked it will load procedure qtrReport

如您所见,它将在“Form View Popup”命令栏中添加项目,当单击该项目时,它将加载过程qtrReport

And use this function to see all Commandbars in Access

并使用此功能查看 Access 中的所有命令栏

Sub ListAllCommandBars()
For i = 1 To Application.CommandBars.Count
    Debug.Print Application.CommandBars(i).Name
Next
End Sub