4

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.

4

1 回答 1

14

试试这个,需要添加到您的加载项中,无论是在模块中还是在 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

确保删除关闭 Excel 的按钮,否则每次打开插件时都会添加一个额外的按钮。

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

您创建的想要从按钮运行的子。

Public Sub MainSub
MsgBox("Hello")
End Sub

您还可以在加载项功能区中添加一个列表框以容纳多个按钮。首先创建一个 MenuItem 作为 type:=msoControlPopup 然后在弹出窗口中添加上面的按钮。

除了这个 VBA 代码之外,您还可以更轻松地转到文件 -> 选项 -> 自定义功能区并添加带有新组的新选项卡并将宏分配给该组。但这仅对您有用,上面的代码将允许任何人安装插件并在打开时自动设置一个按钮。

希望这能回答你的问题。

于 2012-06-25T01:56:11.027 回答