Write Excel Addin with VBA and then Put a button that trigger it

我的梦境 提交于 2019-11-27 14:32:41

Try this, needs to be added to your add-in, either in a module or in ThisWorkbook.

Private Const Button as String = "SomeName"

Sub Auto_Open   'Or Private Sub Workboo_Open() in ThisWorkbook
Dim CmdBar as CommandBar
Dim CmdBarMenu as CommandBarControl
Dim CmdBarMenuItem as CommandBarControl

Set CmdBar = Application.CommandBars("Worksheet Menu Bar")
Set CmdBarMenu = CmdBar.Controls("Tools")   ' Index 6

On Error Resume Next
   Application.DisplayAlerts = False
   CmdBarMenu.Controls(Button).Delete 'Just in case a button with same name already exists
   Application.DisplayAlerts = True
On Error GoTo 0

Set CmdBarMenuItem = CmdBarMenu.Controls.Add(Type:=msoControlButton)
With CmdBarMenuItem
     .Caption = Button
     .OnAction = "MainSub"    'Name of the sub it will call when button is pushed
End With

End Sub

Make sure you delete the button on closing Excel, otherwise an additional one will be added everytime you open your addin.

Sub Auto_Close 'Or Private Sub Workbook_BeforeClose(Cancel As Boolean) in ThisWorkbook
Dim CmdBar as CommandBar
Dim CmdBarMenu as CommandBarControl

Set CmdBar = Application.CommandBars("Worksheet Menu Bar")
Set CmdBarMenu = CmdBar.Controls("Tools")   ' Index 6

On Error Resume Next
   Application.DisplayAlerts = False
   CmdBarMenu.Controls(Button).Delete
   Application.DisplayAlerts = True
On Error GoTo 0

End Sub

Your sub that you have created that you wish to run from button.

Public Sub MainSub
MsgBox("Hello")
End Sub

You can also add a list box in the Add-in ribbon to hold multiple buttons. First create a MenuItem as type:=msoControlPopup then within the popup add buttons as above.

As well as this VBA code, it is much easier for you to go File -> Options -> Customize Ribbon and add a new tab with a new group and assign a macro to that group. But that will only work for you, the above code will allow anyone to install the addin and have a button automate upon opening.

Hope this answers your question.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!