C#Interop.Word 2013在一行内替换子字符串格式多个时间

时间:2013-06-26 18:47:39

标签: c# office-interop

我当前的代码只粗体显示“color”一词的第一次出现。

    public void Foo()
    {
        string text = "color 1, color 2, color 3";

        Paragraph parag = doc.Content.Paragraphs.Add(ref missing);
        parag.Range.Text = text;

        int index = text.IndexOf("color");
        object oStart = parag.Range.Start + index;
        object oEnd = parag.Range.Start + index + 4;

        Range subRange = doc.Range(ref oStart, ref oEnd);
        subRange.Bold = 1;

        parag.Range.InsertParagraphAfter();
    }

我的代码应该更改为“颜色”一词的所有发生,以便句子写成

  
    

颜色 1,颜色 2,颜色 3

  

1 个答案:

答案 0 :(得分:1)

你需要使用for循环..

这是代码:

int i = 0;
int index = text.IndexOf("color", i);
while (index > 0) 
{
    object oStart = parag.Range.Start + index;
    object oEnd = parag.Range.Start + index + 4;

    Range subRange = doc.Range(oStart, oEnd);
    subRange.Bold = 1;

    i = index + 4;
    index = text.IndexOf("color", i);
}

试试这个.......