问题
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