为excel添加自定义菜单及其命令

下面的代码大概是3年前写的,好像是借鉴excelhome上一位大大的代码。

把它放到你需要的xla的thisworkbook中,他在你的工具菜单中添加一项 "自定义命令",并在你点选此菜单时运行程序subname:

Const APPNAME As String = "自定义命令"


Private Sub Workbook_AddinInstall()
'调用CreateMenu添加菜单
   CreateMenu
   MsgBox "已经生成菜单至:工具--自定义命令"
End Sub

Private Sub Workbook_AddinUninstall()
'调用DeleteMenu移除菜单
    DeleteMenu
    MsgBox "已经移除菜单:工具--自定义命令"
End Sub

Sub DeleteMenu()
    Dim XLCommandBar As String
    Dim XLMenu As String
    Dim XLMenuItem As String
    Dim NewMenuItem As String
   
    XLCommandBar = "Worksheet Menu Bar"
    XLMenuItem = ""
    NewMenuItem = APPNAME & "..."
   
    XLMenu = Application.CommandBars(XLCommandBar).FindControl(msoControlPopup, 30007).Caption
    On Error Resume Next
    Application.CommandBars(XLCommandBar).Controls(XLMenu).Controls(XLMenuItem).Controls(NewMenuItem).Delete
   
    Application.CommandBars(XLCommandBar).Controls(XLMenu).Controls(NewMenuItem).Delete
   
   
End Sub
Sub CreateMenu()
   
    Dim NewItem As CommandBarButton
 
    Dim XLCommandBar As String
    Dim XLMenu As String
    Dim XLMenuItem As String
    Dim NewMenuItem As String
  
    XLCommandBar = "Worksheet Menu Bar"
    XLMenu = Application.CommandBars(XLCommandBar).FindControl(msoControlPopup, 30007).Caption '我不敢确定30007这个ID总是ok
    XLMenuItem = ""
    NewMenuItem = APPNAME & "..."
   
    On Error Resume Next
    Application.CommandBars(XLCommandBar).Controls(XLMenu).Controls(XLMenuItem).Controls(NewMenuItem).Delete
    Application.CommandBars(XLCommandBar).Controls(XLMenu).Controls(NewMenuItem).Delete

    On Error GoTo 0
    If XLMenuItem = "" Then
        Set NewItem = Application.CommandBars(XLCommandBar).Controls(XLMenu).Controls.Add
    Else
        Set NewItem = Application.CommandBars(XLCommandBar).Controls(XLMenu).Controls(XLMenuItem).Controls.Add
    End If
    With NewItem
        .Caption = NewMenuItem
        .OnAction = "subname"  '新菜单触发的过程名
        .FaceId = 0
        .BeginGroup = True
    End With
   
    Exit Sub

    If Err <> 0 Then
        MsgBox "菜单创建错误,请重新尝试", vbInformation, "提示"
    End If
End Sub 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值