如何检查命名范围是否在我当前的范围内?

时间:2014-03-14 04:15:20

标签: excel vba excel-vba

我知道如何命名一系列细胞。

例如,如果A1到B2被命名为RangeA而我选择A1到C2,那么无论如何我可以判断RangeA是否在其中?

2 个答案:

答案 0 :(得分:3)

以下是一些可以帮助您的代码:

Sub test()
Dim r1 As Range, r2 As Range, r3 As Range

Set r1 = Range("A1:A5")
Set r2 = Range("A3:A6")
Set r3 = Application.Intersect(r1, r2)

If Not r3 Is Nothing Then
  If r3.Cells.Count = r2.Cells.Count Then
    MsgBox "there is a complete intersection"
  Else
    MsgBox "there is some overlap"
  End If
Else
  MsgBox "there is no overlap"
End If

End Sub

应该是不言自明的。并向@TimWilliams发表评论,并发表评论。

根据您的要求说明

更新

Sub getIntersectingNames(r As Range)
  For Each Nm In ActiveWorkbook.Names
    If Not Application.Intersect(r, Range(Nm)) Is Nothing Then
      MsgBox Nm.Name & " intersects"
    End If
  Next
End Sub

Sub test()
  ' pop up a message box for every range that intersects cell B2:
  getIntersectingNames [B2]
End Sub

Function listIntersectingNames(r As Range)
  Dim result() As String
  ReDim result(1 To ActiveWorkbook.Names.Count)
  Dim matchCount As Integer

  matchCount = 0

  For Each Nm In ActiveWorkbook.Names
    If Not Application.Intersect(r, Range(Nm)) Is Nothing Then
      matchCount = matchCount + 1
      result(matchCount) = Nm.Name
    End If
  Next
  ReDim Preserve result(1 To matchCount)
  listIntersectingNames = result

End Function

Sub test2()
' return an array of names of all ranges that intersect cell B3:
  ans = listIntersectingNames([B3])
  s = ""
  For Each r In ans
    s = s & r & vbCrLf
  Next
  MsgBox s
End Sub

我不太清楚你想要的方式"返回一个名单和#34;,所以我在上面给出了几个选项。如果您能将此应用于您的情况或需要更多信息,请告诉我?

答案 1 :(得分:1)

进一步扩展蒂姆和弗洛里斯所说的内容,见下文:

Dim myNamedRange As Range, mySelection As Range, myIntersect As Range

Set mySelection = Selection '~~> gets your selection
Set myNamedRange = Range("RangeA") '~~> can be declared or directly pass to Intersect
Set myIntersect = Intersect(mySelection, myNamedRange)

    '~~> Then use intersect
If Not myIntersect Is Nothing Then
    If myIntersect.Address = myNamedRange.Address Then
        MsgBox "Your named range is within your selection."
    Else
        MsgBox "Your named range is beyond your selection."
    End If
Else
    MsgBox "Your named range is beyond your selection."
End If

End Sub

这是基于您的实际问题,将命名范围RangeA与选择进行比较 希望这有点帮助。