重新定义段落范围以包括段落中的单词子集

时间:2014-10-10 22:35:32

标签: c# .net ms-word ms-office office-interop

我正在使用Microsoft.Interop.Word / C#以编程方式创建Word文档。在给定的段落中,我需要更改括号“[”和“]”

之间出现的单词的颜色

这些词是可变的。

据我了解,我需要一个Range对象来设置颜色。我使用以下代码,但不起作用:

// 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 个答案:

答案 0 :(得分:0)

SetRange不起作用,因为您无法更改段落的开头或结尾。它只是从它开始的地方开始。您需要一个可以修改的“自有”范围。幸运的是存在属性Duplicate of a Range。正如MSDN所说:By duplicating a Range object, you can change the starting or ending character position of the duplicate range without changing the original range.

首先,我假设包含MS Word namspace:

using Microsoft.Office.Interop.Word;

因此,在计算startPos和endPos之后,您应该将代码更改为(更新):

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;

它应该有效。 (只是不要在endPos上面减少一些行;但你会意识到它)