如何查找指定范围内的所有内部名称范围?
本例中,指定范围为R_2。
我需要找到 R_2 和 R_3。
Dim nm As Name
For Each nm In ThisWorkbook.Names
*** CODE HERE ***
Next nm
我之前使用过以下代码。
Dim nm As Name
Dim rng As Range
Set rng = Range("R_2") 'specified range
For Each nm In ThisWorkbook.Names
If Not Intersect(rng,Range(nm)) Is Nothing Then
*** CODE HERE ***
End If
Next nm
如果我需要查找所有内部范围,但不存在外部范围,它就有效。
也就是说,如果没有范围 R_1,我可以毫无问题地找到 R_2 和 R_3,但如果存在外部范围,则搜索交集是不合适的。
范围的名称可以不同,所以我需要精确地枚举所有范围(每个范围)。
根据建议的答案,我形成了一个解决方案:
Sub Test()
Dim nm As Name
Dim rng As Range
Set rng = Range("R_2") 'example specified range
For Each nm In ThisWorkbook.Names
If nm.RefersToRange.Parent.Name = ActiveSheet.Name Then 'ranges only from the active sheet
If isInside(rng, nm) And Not rng.Name = nm Then Debug.Print nm.Name
End If
Next nm
End Sub
Function isInside(rb As Range, ra As Excel.Name) As Boolean
Dim r As Range
Set r = Intersect(ra.RefersToRange, rb)
If Not r Is Nothing Then
isInside = (ra.RefersToRange.Cells.CountLarge = r.Cells.CountLarge)
Exit Function
End If
End Function
在我的项目中,即使存在与边界相邻的范围,此代码也能完成任务。
要查找指定区域的名称,您需要一个安全循环。从循环的核心,调用执行检查的函数。检查两个区域相交的单元格数量是否等于检查区域的单元格数量。如果是这样,那么受控区域完全在我们原来的区域内。
Public Function getInnerRanges(specificRange As String) As String
Dim nRng As Name, r As Range, rng As Range
Set rng = Range(specificRange)
getInnerRanges = specificRange
For Each nRng In ThisWorkbook.Names
If specificRange <> nRng.Name Then
If isInside(rng, nRng) Then
getInnerRanges = getInnerRanges & "," & nRng.Name
End If
End If
Next
End Function
Public Function isInside(rb As Range, ra As Excel.Name) As Boolean
Dim r As Range
On Error GoTo Lerr
Set r = Intersect(ra.RefersToRange, rb)
If Not r Is Nothing Then
isInside = (ra.RefersToRange.Cells.CountLarge = r.Cells.CountLarge)
Exit Function
End If
On Error GoTo 0
Exit Function
Lerr:
On Error GoTo 0
isInside = False
End Function
Sub example22()
Dim s As String
s = getInnerRanges("R_2")
Debug.Print s
End Sub
一旦获得了角点的坐标,就很容易进行比较。第一种方法针对所有范围测试所有范围。最后一个方法计算值。
您必须决定是否应该与 < and > 或 <= and >= 进行比较。
Sub Test()
Dim nm1 As Name, nm2 As Name
For Each nm1 In ThisWorkbook.Names
For Each nm2 In ThisWorkbook.Names
If nm1.Name <> nm2.Name Then
Debug.Print nm1.Name & " inside of " & nm2.Name & ": " & IsInside(nm1.RefersToRange, nm2.RefersToRange)
End If
Next nm2
Next nm1
End Sub
Function IsInside(InnerRange As Range, OuterRange As Range) As Boolean
Dim InnerLeft As Long
Dim InnerTop As Long
Dim InnerRight As Long
Dim InnerBottom As Long
Dim OuterLeft As Long
Dim OuterTop As Long
Dim OuterRight As Long
Dim OuterBottom As Long
With InnerRange
InnerTop = .Row
InnerLeft = .Column
InnerBottom = .Row + .Rows.Count
InnerRight = .Column + .Columns.Count
End With
With OuterRange
OuterTop = .Row
OuterLeft = .Column
OuterBottom = .Row + .Rows.Count
OuterRight = .Column + .Columns.Count
End With
IsInside = False
If InnerLeft > OuterLeft And InnerRight < OuterRight Then
If InnerTop > OuterTop And InnerBottom < OuterBottom Then
IsInside = True
End If
End If
End Function