Word VBA批量设置字体格式

2018-11-14 19:50

关键词:

这个宏用来在文档中查找(可替换)相应的字眼,并设置字体,颜色等,如加粗文档中所有特定的的词语等。

MS官方文档只能替换查找到的第一个单词,这个宏可以查找替换全部相的字词。


Sub 批量替换字体格式()


Dim mypath, myfile, wApp

Dim i As Integer

Dim findword As String

Dim myStoryRange As Range


findword = "查找的字词"


'选择目录

With Application.FileDialog(msoFileDialogFolderPicker)

    If .Show = False Then Exit Sub

    mypath = .SelectedItems(1) & ""

End With

myfile = Dir(mypath & "*.doc*")

On Error GoTo ERROR1


'循环打开文档

Do While myfile <> ""


    Set wApp = CreateObject("word.application")

    wApp.Visible = True


    With wApp

        '打开word

        .Documents.Open mypath & myfile


        '批量替换字体颜色为白色

        Do

            .Selection.Find.ClearFormatting

            .Selection.Find.Replacement.ClearFormatting

            With .Selection.Find

                .Text = findword

                .Replacement.Text = ""

                .Forward = True

                .Wrap = wdFindContinue

                .Format = True

                .MatchCase = False

                .MatchWholeWord = False

                .MatchByte = False

                .MatchAllWordForms = False

                .MatchSoundsLike = False

                .MatchWildcards = True

            End With

            .Selection.Find.Execute

            If .Selection.Font.Name = "黑体" Then

                Exit Do

            End If

            .Selection.Font.Name = "黑体"

            .Selection.Font.Color = RGB(255, 255, 255)

        Loop

     

     '保存并退出

        .ActiveDocument.Save

        .Quit

    End With


    Set wApp = Nothing

    myfile = Dir

Loop


Exit Sub

ERROR1:

wApp.Application.Quit


End Sub



最后更新:2018-12-02 17:25

0 条回复

说两句