Excel VBA检查是否设置了命名范围

时间:2016-06-03 09:37:01

标签: excel vba excel-vba

我试图确定是否已通过VBA设置了命名范围。命名范围称为LoadedToken,当用户单击特定按钮时,基本上会加载。我用它来证明初始化已经发生。

我有一个功能来检查是否发生了这种情况:

Function ToolIsEnabled()

    ' We check if the R2A add-in has been loaded by detecting the named range
    If ActiveWorkbook.Names("LoadedToken") Is Nothing Then
        ToolIsEnabled = False
    Else
        ToolIsEnabled = True
    End If

End Function

我收到了一个应用程序错误。当然,VBA是不正确的。但是我怎么能真正实现这个目标呢?!

5 个答案:

答案 0 :(得分:4)

Sub Test()
    Debug.Print IsNamedRange("Bumsti")
End Sub

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

OP上下文中的用法可能是

' ...
If IsNamedRange("LoadedToken") Then
    ' ...
End If
' ...

或 - 如果需要设置特定于程序的Bool

' ...
Dim IsTokenLoaded as Boolean
IsTokenLoaded = IsNamedRange("LoadedToken")
' ...

两种结构都在源代码中清楚地表明了你的目标。

答案 1 :(得分:1)

您可以使用错误处理来实现此目的:

scrollX=true

答案 2 :(得分:0)

这将检查ThisWorkbook或命名的工作簿,并返回TRUE / FALSE。

Sub Test()

    MsgBox NamedRangeExists("SomeName")
    MsgBox NamedRangeExists("SomeOtherName", Workbooks("Book1.xls"))

End Sub

Public Function NamedRangeExists(sName As String, Optional Book As Workbook) As Boolean

    On Error Resume Next

        If Book Is Nothing Then
            Set Book = ThisWorkbook
        End If

        NamedRangeExists = Book.Names(sName).Index <> (Err.Number = 0)

    On Error GoTo 0

End Function

编辑: 一个较短的版本,如果它只会查看ThisWorkbook

Public Function NamedRangeExists(sName As String) As Boolean

    On Error Resume Next

        NamedRangeExists = ThisWorkbook.Names(sName).Index <> (Err.Number = 0)

    On Error GoTo 0

End Function

答案 3 :(得分:0)

对于activeworkbook,您也可以调用旧的XLM NAMES()函数:

print(", ".join([str(x) for x in var]))

答案 4 :(得分:0)

按照汤姆的回答,这两行应该可以解决问题:

On Error Resume Next
Set TestRange = ActiveWorkbook.Range("LoadedToken")  'if it does **not** exist this line will be ERROR