Excel VBA - 将子菜单添加到自定义右键单击菜单

时间:2016-07-14 14:58:58

标签: excel vba

长时间观看者,第一次海报。 我有一个右键单击功能的表单,工作正常。 我试图在主右键菜单中添加子菜单以分隔某些功能/命令。我需要/想要插入' Select Case'然而,它是唯一显示顶级菜单。 不知道从哪里开始。任何帮助都很棒

谢谢:)

P.S。如果需要,我很乐意进一步解释。

Sub fzCopyPaste(iItems As Integer)
On Error Resume Next
CommandBars("Custom").Delete
Set PopBar = CommandBars.Add(Name:="Custom", Position:=msoBarPopup, MenuBar:=False, Temporary:=True)

'在主Popbar上添加top_menu:这很正常

Set top_menu = PopBar.Controls.Add(Type:=msoControlButton)
With top_menu
    '.FaceId =
    .Caption = "&Some Commands"
End With

需要将以下子菜单插入顶层菜单 但没有出现:不起作用

Select Case iItems
Case 1  ' Copy and Paste
    Set copy_button = top_menu.Controls.Add(Type:=msoControlButton)
    With copy_button
        .FaceId = 19
        .Caption = "&Copy"
        .Tag = "tCopy"
        .OnAction = "fzCopyOne(true)"
    End With

    Set paste_button = top_menu.Controls.Add(Type:=msoControlButton)
    With paste_button
        .FaceId = 22
        .Tag = "tPaste"
        .Caption = "&Paste"
        .OnAction = "fzCopyOne(true)"
    End With
Case 2 '  Paste Only
    Set paste_button = top_menu.Controls.Add(Type:=msoControlButton)
    With paste_button
        .FaceId = 22
        .Tag = "tPaste"
        .Caption = "&Paste"
        .OnAction = "fzCopyOne(true)"
    End With
End Select

'这里的额外顶级菜单:这很好

    Set paste_button = PopBar.Controls.Add(Type:=msoControlButton)
    With paste_button
        .FaceId = 22
        .Tag = "tPaste"
        .Caption = "Main POP BAR 2"
        .OnAction = "fzCopyOne(true)"
    End With


PopBar.ShowPopup

CommandBars("Custom").Delete
End Sub

1 个答案:

答案 0 :(得分:2)

您将Copy_Button设为等于msoControlButton。如果你想要一个按钮,这是正确的。您想要一个菜单​​,因此您应该将其设置为msoControlPopup。尝试这样的事情:

Set Top_Menu = PopBar.Controls.Add(Type:=msoControlPopup)
With Top_Menu 
    .Caption = "&Some Commands"
    Set MySubMenu = .Controls.Add(Type:=msoControlPopup, before:=1, temporary:=True)
    Select Case iItems
        Case 1
            With MySubMenu
                .Caption = "Submenu Commands"
                With .Controls.Add(Type:=msoControlButton, before:=1, temporary:=True)
                    .FaceId = 19
                    .Caption = "&Copy"
                    .Tag = "tCopy"
                    .OnAction = "fzCopyOne(true)"
                End With

                With .Controls.Add(Type:=msoControlButton, before:=2, temporary:=True)
                    .FaceId = 22
                    .Tag = "tPaste"
                    .Caption = "&Paste"
                    .OnAction = "fzCopyOne(true)"
                End With
            End With
        Case 2
            'etc
    End Select
End With

我用下面的内容删除了“Top_Menu”部分(前3行);它添加了一个额外的按钮,然后是所需的菜单。

Set MySubMenu = PopBar.Controls.Add(Type:=msoControlPopup, before:=1, temporary:=True)
With MySubMenu
    .Caption = "&Some Commands"