确定单元格是否属于命名范围的逻辑测试

Logical test to determine whether a cell is part of a named range

所以我搜索了网络和堆栈溢出,但我找不到任何关于此的信息,主要是因为我的问题有两个部分。第一部分是:逻辑测试以查看单元格是否属于命名范围的一部分,但我们无法将其缩小到一个命名范围,因为我的电子表格中有多个命名范围。第二部分是,一旦我知道单元格在命名范围内,我就想知道该范围的名称。

我想我会创建一个由命名范围对象数组组成的 for 循环,但我也不知道该怎么做。如有任何提示或建议,我们将不胜感激。

假设我们有一个命名范围,例如:

此代码:

Sub WhatsInAName()
    Dim r As Range
    Set r = Intersect(ActiveCell, Range("HomeOnTheRange"))
    If r Is Nothing Then
        MsgBox "active cell is not on HomeOnTheRange"
    Else
        MsgBox "active cell is on HomeOnTheRange"
    End If
End Sub

会告诉你 ActiveCell 是否在上面。

虽然 Gary 的学生答案是正确的,但它没有解决这个需求:

...but we aren't able to narrow it down to one named range, because there are multiple named ranges on my spreadsheet

为此,您需要按照您的猜测迭代 Names 集合。

这是一个修改后的版本,应该对每个命名范围进行迭代。

Option Explicit

Sub SO_Example()
    Dim myCell As Range: Set myCell = Range("A1") 'this is the cell you want to test
    Dim nm As Name 'this is a Name Range object

    'Iterate the names in the workbook
    For Each nm In ActiveWorkbook.Names
        'Use the RefersTo property to get a range object.
        'Refers to adds a '=' sign, which causes an issue so that's why the replace is here
        'There is a probably a cleaner way to do this :)
        Dim nameRng As Range: Set nameRng = Range(Replace(nm.RefersTo, "=", ""))

        'Check to see if the ranges intersect
        If Not Intersect(myCell, nameRng) Is Nothing Then
            Debug.Print nm.Name & " address is " & nm.RefersToLocal & " Intersects myCell at " & myCell.Address
        Else
            Debug.Print nm.Name & " address is " & nm.RefersToLocal & " Does not Intersect myCell at " & myCell.Address
        End If
    Next
End Sub

示例输出:

Another_Name address is =Sheet1!$M Does not Intersect myCell at $A
Name1 address is =Sheet1!$A Intersects myCell at $A
Name2 address is =Sheet1!$A:$A Intersects myCell at $A

另请记住,同一个单元格可能属于多个范围名称。 遍历范围名称时,您可以使用工作簿名称或工作表名称。工作表名称在工作簿级别不可见。 以下是对上述答案的补充。

Dim ws As Worksheet
Dim iCell As Range
Dim r As Range
Dim nRng as Range

Set iCell = ws.Cells(5, 8)

For Each rngName In ws.Names
    Set nRng = ws.Range(rngName)
    Set r = Intersect(iCell, nRng)
    If Not r Is Nothing Then
        MsgBox "active cell is on " & ws.Range(rngName).NAME
    End If
Next rngName

如果这是一次性的情况,我首先只想确保您通过以下方式检查 excel 中的名称管理器:

公式 > 定义的名称 > 名称管理器 (也可以按Ctrl+F3)

进入名称管理器后,您可以按命名范围(如果这是您想要的)或按 "Refers To," 排序,这也可能有帮助。

假设已勾选,这里尝试通过一个由命名范围候选组成的数组来详细说明 Gary 的学生的答案:

Dim PossibleRanges
PossibleRanges = Array("2014Sales", "PossibleRange1", "BeyonceGreatestHits")
Dim i As Integer

For i = 0 To 2 <~~~~~~~ (note the first elmement in the array is indexed at 0)
    If Intersect(ActiveCell, Range(PossibleRanges(i))) Is Nothing Then
    Else MsgBox("Activecell is part of " & PossibleRanges(i))
    End If
Next i

我对此还是很陌生,如果以上内容有任何问题,我深表歉意。祝你好运。