如何通过VBA启用/禁用Excel功能区上的按钮

时间:2016-06-05 15:16:59

标签: excel vba excel-vba

在我正在开发的Excel加载项中,我调用API并通过用户激活密钥发送。如果API识别出密钥,则它返回一个令牌,表示用户已通过身份验证。经过身份验证后,我想启用加载项功能区上的按钮。因此,除非他们获得授权,否则他们不会使用它。

我的功能区xml文件如下所示:

<customUI xmlns="http://schemas.microsoft.com/office/2006/01/customui" onLoad="OnRibbonLoad">

<ribbon>
<tabs>
<tab id="CustomTab" getLabel="GetLabel" insertBeforeMso= "TabDeveloper">

<group id="GroupA" getVisible = "GetVisible" getLabel="GetLabel">
<button id="aButton01" getLabel="GetLabel" onAction="RunMacro"  getImage="GetImage" getSize="GetSize" getScreentip = "GetScreentip" getVisible = "GetVisible" getEnabled="GetEnabled"  />
</group>

<group id="GroupB" getVisible = "GetVisible" getLabel="GetLabel">
<button id="bButton01" getLabel="GetLabel" onAction="RunMacro"  getImage="GetImage" getSize="GetSize" getScreentip = "GetScreentip" getVisible = "GetVisible" getEnabled="GetEnabled" />
<button id="bButton02" getLabel="GetLabel" onAction="RunMacro"  getImage="GetImage" getSize="GetSize" getScreentip = "GetScreentip" getVisible = "GetVisible" getEnabled="GetEnabled" />
<button id="bButton03" getLabel="GetLabel" onAction="RunMacro"  getImage="GetImage" getSize="GetSize" getScreentip = "GetScreentip" getVisible = "GetVisible" getEnabled="GetEnabled" />
</group>

</tab>
</tabs>
</ribbon>
</customUI>

我通过辅助方法为按钮分配各种属性。 GetVisible一个例子:

Sub GetVisible(control As IRibbonControl, ByRef MakeVisible)
'PURPOSE: Show/Hide buttons based on how many you need (False = Hide/True = Show)

Select Case control.ID
  Case "GroupA": MakeVisible = True
  Case "aButton01": MakeVisible = True

  Case "GroupB": MakeVisible = True
  Case "bButton01": MakeVisible = True
  Case "bButton02": MakeVisible = True
  Case "bButton03": MakeVisible = True

End Select

End Sub

我的OnRibbonLoad方法是:

Dim MyRibbonUI As IRibbonUI

Private Sub OnRibbonLoad(ribbonUI As IRibbonUI)

    Dim Authenticate As New AuthenticationClass

    Set MyRibbonUI = ribbonUI

    ' Enable/Disable buttons based on authentication status
    If Authenticate.Authentify = False Then
        ' Lock the Ribbon
        Debug.Print ("Unauthorized!")
    Else
        ' Unlock the Ribbon
        Debug.Print ("Authorized!")
    End If

End Sub

我尝试创建一个GetEnabled方法,我可以调用OnRibbonLoad来切换按钮的可用性,但我无法弄清楚如何调用它:

Sub GetEnabled(control As IRibbonControl, ByRef MakeEnabled)

Select Case control.ID
  Case "GroupA": MakeEnabled = Enabled
  Case "aButton01": MakeEnabled = Enabled

  Case "GroupB": MakeEnabled = Enabled
  Case "bButton01": MakeEnabled = Enabled
  Case "bButton02": MakeEnabled = Enabled
  Case "bButton03": MakeEnabled = Enabled

End Select

End Sub

0 个答案:

没有答案