Monday, May 16, 2011

Formatting the Same Line of Text with Different Word Styles

I was having an issue applying multiple Microsoft Word styles to the same line of text using the Word Interop. Each time I set a style to a substring, Word would apply that style to the entire line of text.

This was happening because the “Style type” was “Paragraph”. Therefore, whenever I set the style to one part of the paragraph, it would apply it to the entire paragraph. To fix this problem, I changed the style type to “Character”.  This allowed me to format a line with multiple styles, as long as each style was a “Character” style type.

If you are curious, below is the C# code I used to add the formatted text:

public void AddFormattedText(
    Word.Range range, string text, string style)
{
    object refStyle = style;

    // Get position to start formatting
    // (before inserting text)
    int startFormat = range.End;

    // Insert the text
    range.InsertAfter(text);

    // Get position to end formatting
    // (after inserting text)
    int endFormat = range.End;

    // Create a new range between the
    // start and end positions
    Word.Range formatMe = range;
    formatMe.SetRange(startFormat, endFormat);

    // Format the range between the
    // start and end positions
    formatMe.set_Style(ref refStyle);
}

No comments:

Post a Comment