Re-defne a Paragraph Range to Include a Subset of

2019-08-31 02:27发布

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);

1条回答
虎瘦雄心在
2楼-- · 2019-08-31 02:51

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:

using Microsoft.Office.Interop.Word;

So after calculating startPos and endPos you should change your code to (UPDATED):

Microsoft.Office.Interop.Word.Range rng = pgf.Range.Duplicate;
rng.MoveEnd(WdUnits.wdCharacter, endPos - rng.Characters.Count);
rng.MoveStart(WdUnits.wdCharacter, startPos);
rng.Font.Color = Microsoft.Office.Interop.Word.WdColor.wdColorRed;

and it should work. (Just don't decrement the endPos some lines above; but you will realize it)

查看更多
登录 后发表回答