所以我搜索了网络并堆栈溢出,我还没有找到任何关于此的内容,主要是因为我的问题有两部分。第一部分是:逻辑测试,以查看单元格是否是命名范围的一部分,但我们无法将其缩小到一个命名范围,因为我的电子表格中有多个命名范围。第二部分是,一旦我知道单元格在命名范围内,我想知道该范围的名称。
我想我会创建一个由Named Range对象组成的for循环,但我也不知道该怎么做。任何提示或建议将不胜感激。
答案 0 :(得分:1)
虽然Gary的学生答案是正确的,但它并没有解决这个问题:
...但我们无法将其缩小到一个命名范围,因为我的电子表格中有多个命名范围
为此,您需要在猜测时迭代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
答案 1 :(得分:0)
假设我们有一个命名范围,如:
此代码:
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
是否在其上。
答案 2 :(得分:0)
还要记住,同一个单元格可能属于多个范围名称。 循环遍历范围名称时,可以使用工作簿名称或工作表名称。工作表名称在工作簿级别上不可见。 以下是上述答案的补充。
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
答案 3 :(得分:0)
如果这是一次性的情况,我首先要确保您通过转到以下方式检查excel中的名称管理器:
公式>定义的名称>名称经理 (您也可以按Ctrl + F3)
一旦进入名称管理器,您可以对命名范围进行排序(如果这是您所追求的)或“引用”,这可能也会有所帮助。
假设已经检查过,这里试图通过一个由命名范围候选者组成的数组来详细阐述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
我对此仍然很新,所以如果上述问题有任何问题我会道歉。祝你好运。