Italic inline word with Interop.Word

Viewed 505

I've starting learning C#, mostly for the purpose of MS Word automation. Using Interop.Word, how can I add a line with words "one two three" with two being italic? The closest I can get is something like this:

//text with some italic words.
para.Range.Text = "one ";
Console.WriteLine(para.Range.Start);
Console.WriteLine(para.Range.End);

// <some magic methods that end the last range and start a new one in place>

para.Range.Text = "two";
para.Range.Font.Italic = 1;
Console.WriteLine(para.Range.Start);
Console.WriteLine(para.Range.End);

// <some magic methods that end the last range and start a new one in place>

para.Range.Text = " three";
Console.WriteLine(para.Range.Start);
Console.WriteLine(para.Range.End);
para.Range.InsertParagraphAfter();

As for the method I need, I tried many things, but none of them worked. The MSDN documentation is very hard to read and omit many important details.

EDIT: I finally made it worked, by creating a new range object for every word. This is about as ugly as I could imagine but as least it works:

        Word.Range rng = word_doc.Range(para.Range.End - 1, para.Range.End);

        rng.Text = "one ";
        Console.WriteLine(rng.Start);
        Console.WriteLine(rng.End);

        rng = word_doc.Range(rng.End - 1, rng.End);
        rng.Text = "two";
        rng.Font.Italic = 1;
        Console.WriteLine(rng.Start);
        Console.WriteLine(rng.End);

        rng = word_doc.Range(rng.End - 1, rng.End);
        rng.Text = " three";
        rng.Font.Italic = 0;
        Console.WriteLine(rng.Start);
        Console.WriteLine(rng.End);
        para.Range.InsertParagraphAfter();
1 Answers
Related