且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

Word VBA:查找行并替换字体

更新时间:2023-02-23 08:18:36

以下代码应在文档中运行,以 Simulation Nr.开头的行并替换整个strong>粗体和斜体的线条字体.

The following code should run over the document, looking for line starts with Simulation Nr. and replace the whole line font with bold and italic.

Sub ReplaceLinesStartWith()

Dim startingWord As String
'the string to search for
startingWord = "Simulation Nr."

Dim myRange As range
'Will change selection to the document start
Set myRange = ActiveDocument.range(ActiveDocument.range.Start, ActiveDocument.range.Start)
myRange.Select

While Selection.End < ActiveDocument.range.End
   If Left(Selection.Text, Len(startingWord)) = startingWord Then
        With Selection.Font
            .Bold = True
            .Italic = True
        End With
    End If

    Selection.MoveDown Unit:=wdLine
    Selection.Expand wdLine

Wend

End Sub

请注意,我对要搜索的字符串进行了硬编码,您可以将其设置为函数参数.

Note that I hardcoded the string to search for, you can set it as function argument instead.