【问题标题】:Check if a CommandBarButton exists检查是否存在 CommandBarButton
【发布时间】:2013-01-12 00:29:19
【问题描述】:

我在我的 VbaProject.OTM 文件的 ThisOutlookSession 中使用以下内容将 2 个自定义按钮添加到新邮件的标准 工具栏:

Dim outl As Object
Dim msg As Object
Set outl = CreateObject("Outlook.Application")
Set msg = outl.CreateItem(0)
msg.Display (False)

Dim objBar As Office.CommandBar
Dim objButton As Office.CommandBarButton

Set objBar = Application.ActiveWindow.CommandBars("Standard")
Set objButton = objBar.Controls.Add(msoControlButton)

With objButton
    .caption = "button1"
    .OnAction = "macro1"
    .TooltipText = "Description"
    .faceId = 487
    .Style = msoButtonIconAndCaption
    .BeginGroup = True
End With

Set objButton = objBar.Controls.Add(msoControlButton)

With objButton
    .caption = "button2"
    .OnAction = "macro2"
    .TooltipText = "Description"
    .faceId = 2525
    .Style = msoButtonIconAndCaption
    .BeginGroup = True
End With

msg.Close 1

问题在于,每次 Outlook 启动时都会添加按钮(我愿意将 OTM 文件部署到的其他计算机需要此按钮)。有没有办法在添加按钮之前检查它是否已经存在?

【问题讨论】:

    标签: vba outlook outlook-2003


    【解决方案1】:

    You 按钮是toolbar 的一部分。因此检查工具栏的存在。

    If IsToolbar("Standard") Then 
      '-- do something
      Else 
      '-- create tool bar and add the buttons
    End If
    

    或者试试这个:

    For Each Contrl in Application.CommandBars("Standard").Controls
       If .Caption <> "button1" then
          '-- create it
       End If
    Next Contrl
    

    根据 OP 的评论进行编辑:

    所以让我们坚持错误捕获...(未经测试的代码,因此您可能必须尝试一下,以获得完全正确的语法)

    Dim ctlCBarControl As CommandBarControl
    On Error Resume Next    
    Set ctlCBarControl = Application.CommandBars("Standard").Controls("button1")
    
       If Err <> 0 Then
          '-- no button exists, you may add it
          Err = 0
       Else
          '-- the button is there.. 
       End If
    End if
    

    * 参考:CommandBar Controls

    【讨论】:

    • +1 寻求帮助。第二个解决方案看起来很完美。顺便说一下,标准是 Outlook 中的默认工具栏,检查它是否存在并没有多大帮助,但循环通过控件应该可以做到。但是,因为这是默认工具栏,所以有很多按钮。每次启动 Outlook 时都会循环播放。这意味着我可能正在寻找更快的解决方案。没有办法直接尝试使用一些 On Error 句柄直接到达右侧按钮?或者我想我可以创建一个新的工具栏。我仍在寻找有关如何执行此操作的指南(创建工具栏,将其放在我想要的位置等)。
    • @dnLL 我认为你最好使用一个新的toolbar,因为你真的可以将这两个按钮添加到其中并随手丢弃它;)(希望这对前端要承受您正在加载的控件/元素..) 我现在真的没有前景来测试试验和错误,我只是根据逻辑/语法输入上面的代码;)什么你可以做的是尝试按照我的编辑来捕捉错误。为您的评论 +1,您确实想出了您可能需要的更快的解决方案。在您尝试err 后告诉我结果如何
    • Controls.Item 允许传递控件名称(字符串)。如果找不到具有该名称的控件,则会引发异常,您可以捕获并插入控件。
    • 谢谢,明天我会试一试,一旦我弄清楚如何创建一个新的工具栏。
    • 选择了那个解决方案,先是On Error Resume Next,然后是On Error Goto 0
    猜你喜欢
    • 2015-10-18
    • 2018-09-10
    • 2011-05-09
    • 2012-10-15
    • 2018-08-22
    • 2012-01-22
    • 2013-06-18
    • 2012-01-17
    • 2012-05-17
    相关资源
    最近更新 更多