Search code examples
c#searchms-wordrangeoffice-automation

Why does all Word.Range object change when changing one of them?


This is actually a XY question but I kind of want answers to both. What I need to solve is X and my solution to it is Y but it doesn't work. I'm working on word automation and using vs10 and msWord10.

I'll start out with X cause it makes the most sense!

X (The real problem):

I got this large dynamic string which contains some words I would like to pick out. The words I would like to pick out is in a tag - see example below.

Example:

Here is some text which could be anything. !#The text I want to get#! Some more text which could be anything !#Some more text I want to get#!

The "!#" is the startTag and "#!" is the endTag

Output:

The text I want to get

Some more text I want to get

Y (My solution to X)

public void doSomething_TEST(string text, Word.Range range)
    {
        string commandsTagStart = "!#";
        string commandsTagEnd = "#!";

        Word.Range range1 = range;
        Word.Range range2 = range;

        range1.Find.Execute(commandsTagStart);
        while (range1.Find.Found)
        {
            if (range1.Text.Contains(commandsTagStart))
            {
                range2.Find.Execute(commandsTagEnd);
                if (range1.End < range2.Start)
                {
                    Word.Range nameRange = document.Range(range1.End, range2.Start);
                }
            }
            range1.Find.Execute(commandsTagStart);
        }

    }

I've had this code running before where it worked perfectly but in that case the range objects where set to the range of the word document and that can't be done this time because I only want to search in the specific Range.

However the problem appears when I first time run the Find.Execute() then it finds the first commandsTagStart and sets the range1 object to the range of that tag which is good but for some reason the range2 object also changes.

Every time I change one of the range objects (range1 or range2) or do something with the objects they both change and I don't have a clue why?

I just need to solve X but I would really appreciate an answer to Y.


Solution

  • You have two references to the same Range. Use:

    Word.Range range2 = range.Duplicate