【问题标题】:How to programmatically add a toolbar button (and OnClick handler) to Excel如何以编程方式将工具栏按钮(和 OnClick 处理程序)添加到 Excel
【发布时间】:2009-02-27 00:39:25
【问题描述】:

如何以编程方式将工具栏(带有按钮)添加到 Excel (2002 年或以后)?

当按钮被点击时,我想要一个处理程序来创建我的 COM 对象并在其上调用方法?

【问题讨论】:

    标签: excel vba button toolbar


    【解决方案1】:

    这是应该适用于 但不包括 Excel 2007 版本的基础,该版本具有完全不同的界面。

    这在您的 ThisWorkbook 模块中:

    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
    

    【讨论】:

    • 这在 O2007 中是否仍然有效,只是创建的任何工具栏都以“插件”功能区结尾?
    • 嗯,是的。但它看起来真的很可怕。最好硬着头皮学习 RibbonX,尽管它过于复杂。
    • 如果要显示已经作为参数传递的文本,请设置Btn.Style = msoButtonIconAndCaptionBtn.Caption = caption
    【解决方案2】:

    您可以write an Excel add-in that creates a toolbar with your button and COM-calling code,然后将您创建的 .xla 文件放到用户的XLStart folder 中。

    【讨论】:

      猜你喜欢
      • 2017-10-28
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-01-03
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多