Reputation: 21
I want to search all bold text occurrences in MS Word 2007 document, and replace each bold "text" with "< text >"
Like following pseudo-code
foreach boldText in WordDocument
{
string replacedText = "< " + boldText + " >";
WordDocument.replace(boldText ,replacedText );
}
WordDocument.save();
Upvotes: 2
Views: 4330
Reputation: 20993
What you could do is something like this:
private void ReplaceBoldText(Microsoft.Office.Interop.Word.Document doc)
{
foreach(Microsoft.Office.Interop.Word.Range rng in doc.StoryRanges)
{
foreach (Microsoft.Office.Interop.Word.Range rngWord in rng.Words)
{
if (rngWord.Bold != 0)
{
rngWord.Bold = 0;
rngWord.Text = "<b>" + rngWord.Text + "</b>";
}
}
}
}
This will change every TEXT to <b>TEXT</b>
. If you want to check each character to see if it is bold you would need to iterate through rngWord.Characters
. You may need some extra work to encapsulate consecutive bold characters, but the basis is as above.
If you are only worrying about whole words then the above will work fine.
Hope this helps.
Upvotes: 4