使用 VB.NET 将 Word 文档文本替换为特定字体

Replacing Word Document Text with Specific Font using VB.NET

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

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 循环之前设置字体(目前已注释掉)并在循环中尝试过。 (当前代码)

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

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

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)