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

后端 未结 1 573
Happy的楠姐
Happy的楠姐 2020-12-03 09:33

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 n

1条回答
  •  [愿得一人]
    2020-12-03 10:03

    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.

    0 讨论(0)
提交回复
热议问题