用VB.NET替换特定字体的Word文档文本

时间:2015-02-10 20:34:10

标签: vb.net ms-word

我很难弄清楚如何使用特定字体替换word文档中的Text。我可以让它找到并替换文本,但它没有使用我指定的字体。

Dim objWord As Word.Application
Dim objDoc As Word.Document

objWord = New Word.Application
objWord.Visible = True
objDoc = objWord.Documents.Open("C:\Users\John.USEI\Desktop\ME551i2.doc")
objWord.Visible = True

'objWord.ActiveWindow.Selection.Font.Name = "WASP LOGMARS MC"
'objWord.ActiveWindow.Selection.Font.Size = "20"

objDoc.Content.Find.Execute(FindText:="MAM", ReplaceWith:="L412F05050", Replace:=Word.WdReplace.wdReplaceAll)
While objDoc.Content.Find.Execute(FindText:="  ", Wrap:=Word.WdFindWrap.wdFindContinue)
    objWord.ActiveWindow.Selection.Font.Name = "WASP LOGMARS MC"
    objWord.ActiveWindow.Selection.Font.Size = "20"
    objDoc.Content.Find.Execute(FindText:="  ", ReplaceWith:=" ", Replace:=Word.WdReplace.wdReplaceAll, Wrap:=Word.WdFindWrap.wdFindContinue)
End While

我尝试在While循环之前设置字体(当前已注释掉)并在循环中尝试了它。 (现行代码)

是否可以指定要替换的字体?

1 个答案:

答案 0 :(得分:0)

您可以在查找对象上设置替换字体:

objWord.Selection.Find.ClearFormatting()
objWord.Selection.Find.Replacement.ClearFormatting()
objWord.Selection.Find.Replacement.Font.Color = Word.WdColor.wdColorRed
objWord.Selection.Find.Replacement.Font.Size = 25
With objWord.Selection.Find
    .Text = "John"
    .Replacement.Text = "J2"
    .Forward = True
    .Format = True
    .MatchCase = False
    .MatchWholeWord = False
    .MatchWildcards = False
    .MatchSoundsLike = False
    .MatchAllWordForms = False
End With
objWord.Selection.Find.Execute(Replace:=Word.WdReplace.wdReplaceAll)