7

详细地说,假设我的工作簿中有两个命名范围。两个命名范围具有相同的名称(比如说“myName”),但一个范围限定为 Sheet1,另一个范围限定为工作簿。

给定命名范围的名称(字符串),我想获取工作簿级别的命名范围。

如果我使用本机调用:wb.Names.Item("myName"),它将返回工作表范围的命名范围。

相反,如果我这样做:wb.Names.Item("Sheet1!myName"),那显然会返回工作表范围的名称范围。我发现我可以使用它来指定特定于工作表的工作表,但不能指定工作簿。

无论如何我可以指定我想要工作簿范围吗?

我的解决方法目前正在遍历所有名称的列表,并比较 .Name 属性以获取工作簿范围命名范围。这是因为 .Name 属性附加了一个“Sheet1!”。到工作表范围命名范围。然而,这样做成本很高,我想避免它。

4

1 回答 1

1

When we (JKP and myself) were writing Name Manager we specifically added a filter and warning message for Duplicate Global/Local Names because this Excel object model behaviour you mention leads to hard to detect bugs.

So my recommendation is never to use duplicate Global/Local Names.

We use code to detect if a name is duplicate global/local with the parent of the local name active and then switch sheets if necessary. The optimised VBA code we use to find the local version of a global name is this: its reasonably fast unless you have several tens of thousands of names -

    Function FindNameLocal(oSheet As Worksheet, sName As String) As Name
        Dim oName As Name
        Dim strLocalName As String
        Dim strLocalNameNoQuote
        Dim strName As String
        Set FindNameLocal = Nothing
        If Len(sName) > 0 And Not oSheet Is Nothing And oSheet.Names.Count > 0 Then
            On Error Resume Next
            strLocalName = "'" & oSheet.Name & "'!" & sName
            strLocalNameNoQuote = oSheet.Name & "!" & sName
            Set FindNameLocal = oSheet.Names(strLocalName)
            If Err <> 0 Or (FindNameLocal.NameLocal <> strLocalName And FindNameLocal.NameLocal <> strLocalNameNoQuote) Then
                On Error GoTo 0
                Set FindNameLocal = Nothing
                For Each oName In oSheet.Names
                    strName = oName.Name
                    If Len(strLocalName) = Len(strName) Or Len(strLocalNameNoQuote) = Len(strName) Then
                        If strName = strLocalName Or strName = strLocalNameNoQuote Then
                            Set FindNameLocal = oName
                            GoTo GoExit
                        End If
                    End If
                Next
            End If
        End If
GoExit:
    End Function
于 2012-10-10T08:14:54.953 回答