C# Microsoft.Office.Interop.Word

ぐ巨炮叔叔 提交于 2020-01-06 05:45:08

问题


I'm using Microsoft.Office.Interop.Word with C#. I know that you can set the text to be bold by using Range.Font.Bold=1. My problem is that I have a long sentence and I have to make some words bold in it, not the whole sentence. If my sentence is "Would you like to have responses to your questions sent to you via email?", I would like "have responses" to be bold.

With this example I can bold only one word (by looping through the whole word document):

foreach(Microsoft.Office.Interop.Word.Range w in oDoc.Words)
{
    if (w.Text == "Something")
         w.Font.Bold = 1;
}

But this is just for one word, how can I make bold two, three or more consecutive words in a sentence.


回答1:


No need to loop through the whole document. Use Word.WdReplace.wdReplaceAll, something similar to this:

private void SearchReplace()
{
    Word.Find findObject = Application.Selection.Find;
    findObject.ClearFormatting();
    findObject.Text = "find me";
    findObject.Replacement.ClearFormatting();
    findObject.Replacement.Text = "Found";

    object replaceAll = Word.WdReplace.wdReplaceAll;
    findObject.Execute(ref missing, ref missing, ref missing, ref missing, ref missing,
        ref missing, ref missing, ref missing, ref missing, ref missing,
        ref replaceAll, ref missing, ref missing, ref missing, ref missing);
}

You can read more about it here: http://msdn.microsoft.com/en-us/library/f65x8z3d.aspx

Hope it helps!




回答2:


Look at this:

C#: Searching a Text in Word an getting the range of the result

Then you can make bold the found range.



来源:https://stackoverflow.com/questions/9840199/c-sharp-microsoft-office-interop-word

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!