Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

I have written a simple excel add-in with VBA, it contains a form and related codes. after saving it as add-in and then installing it in Excel, nothing happened!

I need to put a button somewhere in ribbons that trigger my add-in, you know like "Solver". I really need it, pleas tell me how.

I really appreciate any suggestions.

like image 254
Bob.S.P Avatar asked Dec 08 '22 23:12

Bob.S.P


1 Answers

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.

like image 107
Rory Avatar answered Dec 28 '22 07:12

Rory