1

我设置了一个用户 Find+Replace All 宏,以查找和替换特定文本的所有实例,它按计划工作。

但是,当我将该操作记录为宏并运行它时,它只替换了查找文本的第一个实例。我究竟做错了什么?

记录的代码在下面。

Sub Macro25()
'
' Macro25 Macro
'
'

    Selection.Find.ClearFormatting
    Selection.Find.Style = ActiveDocument.Styles("Body Text")
    With Selection.Find.ParagraphFormat
        With .Shading
            .Texture = wdTextureNone
            .ForegroundPatternColor = wdColorBlack
            .BackgroundPatternColor = wdColorBlack
        End With
        .Borders.Shadow = False
    End With
    Selection.Find.Replacement.ClearFormatting
    Selection.Find.Replacement.Style = ActiveDocument.Styles("Body Text 2")
    With Selection.Find.Replacement.ParagraphFormat
        With .Shading
            .Texture = wdTextureNone
            .ForegroundPatternColor = wdColorBlack
            .BackgroundPatternColor = wdColorBlack
        End With
        .Borders.Shadow = False
    End With
    With Selection.Find
        .Text = ""
        .Replacement.Text = ""
        .Forward = True
        .Wrap = wdFindContinue
        .Format = True
        .MatchCase = False
        .MatchWholeWord = False
        .MatchKashida = False
        .MatchDiacritics = False
        .MatchAlefHamza = False
        .MatchControl = False
        .MatchWildcards = False
        .MatchSoundsLike = False
        .MatchAllWordForms = False
    End With
    Selection.Find.Execute Replace:=wdReplaceAll
End Sub
4

3 回答 3

2

宏仅替换您在运行宏时选择的文本。这就是这个词的Selection意思。

如果您希望对整个文档进行查找/替换,则需要Selection在宏中替换为ActiveDocument.

于 2013-10-29T01:09:52.600 回答
0

感谢你的回答。所以继续前进......下面是我自己编写的代码。它基于宏记录器生成的代码。我的代码没有使用相同的选择思想。它使用一个 rng Range 对象。

但是我得到了同样的效果:它只找到了某事的第一个实例。

Function ExecReplaceStyle(strSourceStyle As String, strDestinationStyle As String) As Integer
        On Error GoTo ErrorHandler

        Dim rng As Range
        Dim ret As Integer

        ExecReplaceStyle = 0
        Set rng = docActiveDoc.Range

        With rng.Find
            .ClearFormatting
            .Style = ActiveDocument.Styles(strSourceStyle)
            .Replacement.Style = ActiveDocument.Styles(strDestinationStyle)
            .Text = ""
            .Replacement.Text = ""
            .Forward = True
            .Wrap = wdFindContinue
            .Forward = True
            .Format = True
            .MatchCase = False
            .MatchWholeWord = False
            .MatchKashida = False
            .MatchDiacritics = False
            .MatchAlefHamza = False
            .MatchControl = False
            .MatchWildcards = False
            .MatchSoundsLike = False
            .MatchAllWordForms = False
        End With

        rng.Select
        rng.Find.Execute Replace:=wdReplaceAll


        ExecReplaceStyle = ret

        Exit Function

    ErrorHandler:
        ExecReplaceStyle = Err.Number
        ErrDescription = Err.Description
        Resume Next
    End Function
于 2013-10-29T23:00:58.140 回答
0

Selection.Find.Execute Replace:=wdReplaceAll 之后应该在End With整个文档中搜索和替换。

于 2015-07-21T05:52:18.023 回答