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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With