如果VBA中存在特定工作表,如何在Excel中禁用功能区按钮

时间:2016-06-07 21:24:19

标签: excel vba excel-vba

我正在构建一个Excel加载项,允许用户与PowerPoint交互并导出数据。用户可以通过功能区中的按钮选择将模板插入现有工作簿。当他们单击此按钮时,该按钮将被禁用,因为您在一个工作簿中不能有两个模板。

然后,用户可以保存他们的工作簿,稍后再回来。我的问题是我需要检测他们是否已将模板插入到现有工作簿中,并且我通过尝试检测是否存在命名范围(称为LoadedToken)来执行此操作。

我遇到的问题是功能区的onLoad功能和VBA类Auto_Open在大型工作簿完全加载之前启动。因此,我实际上并没有检测到模板是否存在,并且实际上无法禁用该按钮。

Excel中的事件是否可以在工作表级别调用(如worksheet_open)但在类中检测到?

我的代码是:

'''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''
' When the Ribbon loads
'''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''
Private Sub OnRibbonLoad(ribbonUI As IRibbonUI)

    Set MyRibbonUI = ribbonUI
    Dim Authenticate As New AuthenticationClass

    On Error Resume Next

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

    ' If the template doesn't exist then disable a grouping on the ribbon
    If TemplateExists = False Then
        Call RefreshRibbon(Tag:="Grouping1")
    Else
        Call RefreshRibbon(Tag:="Grouping2")
    End If

End Sub

'''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''
' Check if the Template sheet is visible and prevent other buttons from working
'''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''
Public Function TemplateExists()

    Dim Helpers As New HelpersClass

    If Helpers.IsNamedRange("LoadedToken") Then
        TemplateExists = True
    Else
        TemplateExists = False
    End If

End Function


'''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''
' From the Helpers Class - Check if a named range exists
'''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''
Function IsNamedRange(RName As String) As Boolean

    Dim N As name

    IsNamedRange = False

    For Each N In ActiveWorkbook.Names
        If N.name = RName Then
            IsNamedRange = True
            Exit For
        End If
    Next

End Function

注意:身份验证类只是连接到我的API的另一个类。

0 个答案:

没有答案