简体   繁体   中英

C# Microsoft.Office.Interop.Word

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.

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!

Look at this:

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

Then you can make bold the found range.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM