Results 1 to 3 of 3
  1. #1
    New Lounger
    Join Date
    Sep 2002
    Location
    Green Bay, Wisconsin, USA
    Posts
    17
    Thanks
    0
    Thanked 0 Times in 0 Posts

    Test: Is selection in range? (VBA - Excel 2003)

    I want to test to see if the selection is within the limits of a specified range. For example, if the range is A14 and the selection is B3:C3, the result would be true, but if the selection is B3:B5, the result would be false. How do I code it?

  2. #2
    Plutonium Lounger
    Join Date
    Mar 2002
    Posts
    84,353
    Thanks
    0
    Thanked 29 Times in 29 Posts

    Re: Test: Is selection in range? (VBA - Excel 2003)

    Try this function:

    Function SelectionInRange(rng As Range) As Boolean
    If Intersect(Selection, rng) Is Nothing Then
    SelectionInRange = False
    Else
    SelectionInRange = (Intersect(Selection, rng).Address = Selection.Address)
    End If
    End Function

    Here is a simple example of its use:

    Sub Test()
    If SelectionInRange(Range("A14")) Then
    MsgBox "Selection is (entirely) within A14", vbInformation
    Else
    MsgBox "Selection is not (entirely) within A14", vbInformation
    End If
    End Sub

    You can replace the MsgBox instructions with whatever you want.

  3. #3
    New Lounger
    Join Date
    Sep 2002
    Location
    Green Bay, Wisconsin, USA
    Posts
    17
    Thanks
    0
    Thanked 0 Times in 0 Posts

    Re: Test: Is selection in range? (VBA - Excel 2003)

    Thanks Hans.

    After I posted the question I came across a solution in a book by John Walkenbach:

    InRange = False
    If Union(rng,Selection).Address =Selection.Address Then
    InRange=True
    End If

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •