逻辑testing,以确定一个单元是否是命名范围的一部分

所以我search了networking和堆栈溢出,我一直没有find任何东西,主要是因为我的问题有两个部分。 第一部分是:逻辑testing,看是否一个单元格是命名范围的一部分,但我们无法将其缩小到一个命名范围,因为我的电子表格中有多个命名范围。 第二部分是,一旦我知道单元格在命名范围内,我想知道该范围的名称。

我想我会做一个由命名的范围对象数组的循环,但我也不知道如何做到这一点。 任何提示或build议,将不胜感激。

虽然加里的学生答案是正确的,但它并没有解决这个问题:

…但我们无法将其缩小到一个命名范围,因为我的电子表格中有多个命名范围

为此,您需要按照您猜测的方式迭代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$5 Does not Intersect myCell at $A$1 Name1 address is =Sheet1!$A$1 Intersects myCell at $A$1 Name2 address is =Sheet1!$A$1:$A$2 Intersects myCell at $A$1 

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

在这里输入图像说明

此代码:

 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是否在它上面。

另外请记住,同一个单元格可能属于多个范围名称。 循环范围名称时,可以使用工作簿名称或工作表名称。 工作表级别上不显示工作表名称。 以下是对以上答案的补充。

 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中检查了名称pipe理器,方法是:

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

一旦在名称pipe理器中,您可以将其命名为范围(如果这就是您所追求的内容),也可以通过“引用”(也可能有所帮助)进行sorting。

假设已经被检查过了,这里试图通过一个由命名范围候选人组成的数组来详细说明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 

我还是很新的,所以我很抱歉,如果上面有任何问题。 祝你好运。