I'm using Microsoft.Interop.Word / C# to programmatically create a Word document. In a given paragraph, I need to change the color of words that occur between brackets "[" and "]"
The words are variable.
As I understand it, I need a Range object in order to set colors. I'm using the following code, which does not work:
// Add the paragraph.
Microsoft.Office.Interop.Word.Paragraph pgf = document.Paragraphs.Add();
// Insert text into the paragraph.
pgf.Range.InsertBefore("JIRA Issue: " + jiraIssueId + " [" + statusName + "]");
//Get start and end locations of the brackets.
//These will define the location of the words to which I will apply colors.
int startPos = pgf.Range.Text.IndexOf("[") + 1;
int endPos = pgf.Range.Text.IndexOf("]") - 1;
/* Attempt to change range start and end positions,
so the range contains just the words between brackets.
I've tried two methods.
*/
// The following line does not work.
pgf.Range.SetRange(startPos, endPos);
// And the following lines do not work either
pgf.Range.Start = startPos;
pgf.Range.End = endPos;
// Attempt to Change color. The following line changes the color of entire paragraph:
pgf.Range.Font.Color = Microsoft.Office.Interop.Word.WdColor.wdColorRed;
/* The following always prints the entire contents of the paragraph,
and not just the words between the brackets. So my attempts at narrowing
the range were not successful.
*/
Console.WriteLine(pgf.Range.Text);
The SetRange doesn't work because you can't change beginning or ending of a paragraph. It just begins where it begins. You need an "own" range that you can modify. What a luck there exists the property Duplicate of a Range. As MSDN says:
By duplicating a Range object, you can change the starting or ending character position of the duplicate range without changing the original range.
First I assume that the MS Word namspace is included:
So after calculating startPos and endPos you should change your code to (UPDATED):
and it should work. (Just don't decrement the endPos some lines above; but you will realize it)