Question

Anyone knows how can I change the text of a Word.Range object but still keeping it's format? For example if I have "this text" and I change it to "that txt", txt will still be in bold.

I'm looking for a way to change the whole text of the range, not just a single word, as I'm getting the new text from an independent API, I can assume that the new text and the old text have the same number of words.

This is what I got so far:

    for (int i = 0; i < oldWords.Length; i++)
    {
        if (oldWords[i] == newWords[i])
            continue;

        object Replace = WdReplace.wdReplaceOne;
        object FindText = oldWords[i];
        object ReplaceWith = newWords[i];
        var success = Sentence.Find.Execute(parameters stub);
    }            

But for some reason, it only succeeds in the first Execute, because the range selection remains on the found word.

Edit: got it, after each execute, I had restore the original end position of my Range.

Thanks.

Was it helpful?

Solution

You can't use the Execute method to change the text with formatting. You can do it like:

Range rng=doc.Content;
rng.Find.Execute(ref finding, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing)

//if this method returns true, you will get the range at the finding location.
if(rng.Find.Found)
{
  rng.Text='sth';
  rng.Bold=0;
}

Maybe this can help you.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top