如何在 Office Interop Word 中查找单词并将其更改为斜体
How to Find and change words to Italic in Office Interop Word
我需要找到所有出现的特定单词并将它们设为斜体。
我可以很容易地找到每个单词的第一次出现,但是我不能用 while 循环,它会创建一个无限循环,就好像设置起始范围不会更新范围一样......也许我很傻但是这里是我的逻辑:
第一次出现,
设为斜体,
在第一次出现后将起始范围设置为下一个字符,
重复直到不再出现...
appWord = new Microsoft.Office.Interop.Word.Application();
wordDocument = appWord.Documents.Open("pathToFile", Type.Missing, false);
Microsoft.Office.Interop.Word.Range rng = wordDocument.Range();
string[] latinTerms = new []{"inter alia","invicta" };
for (int i = 0; i < latinTerms.Length; i++)
{
while (rng.Text.IndexOf(latinTerms[i]) != -1)
{
int start = rng.Text.IndexOf(latinTerms[i]);
int end = start + latinTerms[i].Length;
Microsoft.Office.Interop.Word.Range tmpRange = wordDocument.Range(start, end);
tmpRange.Select();
Microsoft.Office.Interop.Word.Selection currSel = appWord.Selection;
currSel.ItalicRun();
rng.Start = end + 1;
}
}
我使用 Find.Execute 替换字符和字符串,效果很好,但我还没有找到将字符和字符串更改为斜体的方法...
您似乎对字体 class 的 Italic 属性 感兴趣。
有关示例代码,请参阅 Word 2007 VBA - Making some text BOLD & other ITALIC。
private void FindAndItalicize(Microsoft.Office.Interop.Word.Application doc, object findText)
{
var rng = doc.Selection.Range;
while(rng.Find.Execute(findText))
{
rng.Font.Italic = 1;
}
}
我需要找到所有出现的特定单词并将它们设为斜体。 我可以很容易地找到每个单词的第一次出现,但是我不能用 while 循环,它会创建一个无限循环,就好像设置起始范围不会更新范围一样......也许我很傻但是这里是我的逻辑:
第一次出现, 设为斜体,
在第一次出现后将起始范围设置为下一个字符,
重复直到不再出现...
appWord = new Microsoft.Office.Interop.Word.Application();
wordDocument = appWord.Documents.Open("pathToFile", Type.Missing, false);
Microsoft.Office.Interop.Word.Range rng = wordDocument.Range();
string[] latinTerms = new []{"inter alia","invicta" };
for (int i = 0; i < latinTerms.Length; i++)
{
while (rng.Text.IndexOf(latinTerms[i]) != -1)
{
int start = rng.Text.IndexOf(latinTerms[i]);
int end = start + latinTerms[i].Length;
Microsoft.Office.Interop.Word.Range tmpRange = wordDocument.Range(start, end);
tmpRange.Select();
Microsoft.Office.Interop.Word.Selection currSel = appWord.Selection;
currSel.ItalicRun();
rng.Start = end + 1;
}
}
我使用 Find.Execute 替换字符和字符串,效果很好,但我还没有找到将字符和字符串更改为斜体的方法...
您似乎对字体 class 的 Italic 属性 感兴趣。
有关示例代码,请参阅 Word 2007 VBA - Making some text BOLD & other ITALIC。
private void FindAndItalicize(Microsoft.Office.Interop.Word.Application doc, object findText)
{
var rng = doc.Selection.Range;
while(rng.Find.Execute(findText))
{
rng.Font.Italic = 1;
}
}