如何在VBA上下文菜单中正确实现事件?

时间:2014-07-30 10:29:33

标签: vba events ms-access event-handling contextmenu

我尝试通过CommandBarButton-Event调用函数。 到目前为止,Code看起来很好,我也没有错误,但没有任何反应。我究竟做错了什么? 我的代码看起来像这样:

Private Sub Main()
    ContextMenu1
    CommandBars("MyListControlContextMenu").ShowPopup
End Sub

Private Sub ContextMenu1()
    Dim MenuItem As CommandBarPopup
    On Error Resume 
    NextCommandBars("MyListControlContextMenu").Delete
    On Error GoTo 0

    With CommandBars.Add(Name:="MyListControlContextMenu", Position:=msoBarPopup, MenuBar:=False, Temporary:=True)
        Set MenuItem = .Controls.Add(Type:=msoControlPopup)
        With MenuItem
            .Caption = "main"
            Dim MenuButton As CommandBarButton
            Set MenuButton = MenuItem.Controls.Add(Type:=msoControlButton)
            With MenuButton
                .Caption = "sub"
                .OnAction = "Test1"
            End With
        End With
    End With
End Sub

Private Sub Test1()
    MsgBox "test", vbOKOnly, "test"
End Sub

1 个答案:

答案 0 :(得分:1)

在contextmenu中实现事件时,似乎MS-Access 2010 VBA的正确语法如下所示:

Sub MyContextMenuConstructor()
    ...
    With MenuButton
        .Caption = "myCaption"
        .OnAction = "=MyFunction('" & myParameter & "')"
    End With
    ...
End Sub

Private Function MyEvent(myInputParameter As String)
    MsgBox myInputVariable, vbOKOnly
End Function

记住:

- What ever called by the Event, needs to be a Function, no Sub; 
- It needs to be called with brackets, even if you do not pas a parameter; 
- When you call the Function, you must have an '=' before its name and you have to have an apostrophe before and after your Parameter. Also allways place a Whitespace between '&' and '"', since VBA doesn't seem to be that clever.