How to programmatically add a toolbar button (and an OnClick handler) in Excel

How to programmatically add a toolbar (with buttons on it) in Excel (2002 or later)?

When the button is pressed, do I want the handler to create my COM object and call the method on it?

+3
source share
2 answers

This is the foundation of what should work with versions prior to , but not including, Excel 2007, which has a completely different interface.

This is included in your ThisWorkbook module:

Private Sub Workbook_BeforeClose(Cancel As Boolean)
    DeleteCommandBar
End Sub
Private Sub Workbook_Open()
    ShowToolbar
End Sub

, , , . OnClick, , .

Private Const TOOLBARNAME = "MyFunkyNewToolbar"

Public Sub ShowToolbar()
' Assumes toolbar not already loaded '
    Application.CommandBars.Add TOOLBARNAME
    AddButton "Button caption", "This is a tooltip", 526, "NameOfASubInYourVBACode"
    ' call AddButton more times for more buttons '
    With Application.CommandBars(TOOLBARNAME)
        .Visible = True
        .Position = msoBarTop
    End With
End Sub

Private Sub AddButton(caption As String, tooltip As String, faceId as Long, methodName As String)
Dim Btn As CommandBarButton
    Set Btn = Application.CommandBars(TOOLBARNAME).Controls.Add
    With Btn
        .Style = msoButtonIcon
        .FaceId = faceId ' choose from a world of possible images in Excel: see http://www.ozgrid.com/forum/showthread.php?t=39992 '
        .OnAction = methodName
        .TooltipText = tooltip
    End With        
End Sub

Public Sub DeleteCommandBar()
    Application.CommandBars(TOOLBARNAME).Delete
End Sub
+7

Excel, COM-, .xla user XLStart.

+2

Source: https://habr.com/ru/post/1703932/


All Articles