none
VSTO | Word | Range compare RRS feed

  • Question

  • Hi,

    I'm trying to work out if two ranges in Word intersect. I'm just interested in whether they intersect or not, I don't need to know how they intersect. I originally thought this would be easy, all I need to do is compare the start and end values and in a simple text document his is sufficient. The problem I have is with text boxes. If I start with a new document and add "Hello, World" on the first line, then add a text box containing "Hello, World", then compare the range start / end values for both "Hello, World",s you end up with the same numbers.

    Is it possible to differentiate the two ranges? How does the range in the text box know it's within a text box?

    Many thanks for any pointers that can be provided.

    Martin

    Thursday, August 2, 2018 4:20 PM

All replies

  • By default, text boxes are inserted as floating shapes, which means they are anchored to a paragraph mark. If a text range you are comparing ends with a paragraph mark, that mark may have a Text Box or any other floating shape attached to it, and then the ending position of the text range is the starting position of the shape range.

    Consider adding some conditional logic code that will alert you to this situation. Below are two examples.

        If Selection.Range.ShapeRange.Count > 0 Then
            Debug.Print "Selection includes a shape"
        End If
        If Asc(Selection.Characters.Last) = 13 Then
            Debug.Print "Selection ends with a paragraph mark"
        End If
    


    Kind Regards, Rich ... http://greatcirclelearning.com

    Saturday, August 4, 2018 9:13 PM
  • There's another way to check whether ranges intersect: by using the InRange method:

    Sub CheckRangeIntersections()
        Dim rng1 As Word.Range
        Dim rng2 As Word.Range
        Dim doc As Word.Document
        
        Set doc = ActiveDocument
        Set rng1 = doc.content
        Set rng2 = doc.Shapes(1).TextFrame.TextRange
        
        If rng1.InRange(rng2) Then
            Debug.Print "rng1 is in rng2"
        ElseIf rng2.InRange(rng1) Then
            Debug.Print "rng2 is in rng1"
        Else
            Debug.Print "The ranges don't touch"
        End If
    End Sub
    

    Using the sample code, there is no intersection of the content of a Shape with the content of the document.


    Cindy Meister, Office Developer/Word MVP, <a href="http://blogs.msmvps.com/wordmeister"> my blog</a>

    Sunday, August 5, 2018 9:16 AM
    Moderator