VBA about "word toolbar"

今天做文档,用公司的TOOLBAR进行版本信息修改,觉得很棒,就搜索了下怎样给WORD添加TOOLBAR的实现方法,特此记录。


Sub AddNewCB()
   Dim myCommandBar As CommandBar, myCommandBarCtl As CommandBarControl
   On Error GoTo AddNewCB_Err

  Set myCommandBar = CommandBars.Add(Name:="Sample Toolbar", Position:= _
      msoBarFloating)
   myCommandBar.Visible = True

  Set myCommandBarCtl = myCommandBar.Controls.Add(msoControlComboBox)
   With myCommandBarCtl
      .Caption = "Drop Down"
      .Width = 300
      .AddItem "Fred", 1
      .AddItem "2012", 2
      .DropDownWidth = 300
      .OnAction = ""

   End With
   Exit Sub
AddNewCB_Err:
   MsgBox "Error " & Err.Number & vbCr & Err.Description
   Exit Sub
End Sub


Function AddRemoveButton()
   Dim myCommandBar As CommandBar, CBCombo As CommandBarComboBox
   Dim CBNewButton As CommandBarButton
   On Error GoTo AddRemoveButton_Err
   Set myCommandBar = CommandBars("Sample Toolbar")
   Set CBCombo = myCommandBar.Controls(3)
   Select Case CBCombo.ListIndex
      Case 1
         Set CBNewButton = myCommandBar.Controls.Add(Type:=msoControlButton)
         With CBNewButton
            .Caption = "New Button"
            .Style = msoButtonCaption
            .BeginGroup = True
            .Tag = "New Button"
            .OnAction = "=MsgBox(""This is a new button!"")"
         End With
      Case 2
         Set CBNewButton = myCommandBar.FindControl(Tag:="New Button")
         CBNewButton.Delete
   End Select
   Exit Function
AddRemoveButton_Err:
   If Err.Number = 91 Then
      MsgBox "Cannot remove button that does not exist!"
      Exit Function
   Else
     MsgBox "Error " & Err.Number & vbCr & Err.Description
     Exit Function
   End If
End Function


  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
要在 Word VBA 中创建工具栏和菜单,可以按照以下步骤进行操作: 1. 打开 Word 文档并按下 Alt + F11 键盘快捷键打开 VBA 编辑器。 2. 在 VBA 编辑器中,选择“插入” -> “模块”,打开新的代码模块。 3. 在模块中编写 VBA 代码来创建工具栏和菜单。例如,以下代码将创建一个名为“Custom Toolbar”的工具栏,并在其上添加一个名为“Custom Menu”的菜单: ``` Sub CreateToolbarAndMenu() Dim cb As CommandBar Dim cbc As CommandBarControl Dim cbp As CommandBarPopup ' Create custom toolbar Set cb = Application.CommandBars.Add(Name:="Custom Toolbar", _ Position:=msoBarTop, Temporary:=True) ' Add custom menu to toolbar Set cbc = cb.Controls.Add(Type:=msoControlPopup) cbc.Caption = "Custom Menu" ' Add commands to custom menu Set cbp = cbc.Controls.Add(Type:=msoControlButton) cbp.Caption = "Say Hello" cbp.OnAction = "SayHello" End Sub ``` 4. 在代码模块中添加一个名为“SayHello”的 VBA 子过程,在该子过程中添加要执行的操作。例如,以下代码将在单击“Say Hello”按钮时在 Word 中显示一个消息框: ``` Sub SayHello() MsgBox "Hello, world!" End Sub ``` 5. 在 VBA 编辑器中,按下 F5 键运行 CreateToolbarAndMenu 子过程。这将创建自定义工具栏和菜单,并将“Say Hello”按钮添加到菜单中。 完成以上步骤后,您可以在 Word 中看到新创建的自定义工具栏和菜单。单击“Custom Menu”将显示“Say Hello”按钮,单击该按钮将显示一个消息框。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值