3

我正在尝试搜索 Word 文档并用指定的值替换特定的字符串(现在使用硬编码的“Special”值)。该宏清楚地表明它在 Word 编辑器中找到了正确的文本,但替换功能不起作用。这是我绝对的第一次 VBA 体验,所以如果可能的话,我希望能得到一些帮助。以下代码是宏...

    Sub Test()
'
' Test Macro
'
'
    Documents.Open FileName:="C:\Users\abensch\Documents\NANTDocMerge\DMID - Backups\System Clock Ability.docx", _
        ConfirmConversions:=False, _
        ReadOnly:=False, AddToRecentFiles:=False, _
        PasswordDocument:="", PasswordTemplate:="", _
        Revert:=False, WritePasswordDocument:="", _
        WritePasswordTemplate:="", _
        Format:=wdOpenFormatAuto, _
        XMLTransform:=""
    Selection.Find.ClearFormatting
    Selection.Find.Replacement.ClearFormatting
    With Selection.Find
        .Text = "Special"
        .Replacement.Text = "Potato"
        .Forward = True
        .Wrap = wdFindContinue
        .Format = False
        .MatchCase = False
        .MatchWholeWord = False
        .MatchWildcards = False
        .MatchSoundsLike = False
        .MatchAllWordForms = False
    End With
    Selection.Find.Execute

End Sub

我不确定 Select.Find 中的大多数指定参数是否是必需的,并且删除它们似乎不会影响宏的性能,但我想我会把它们留在里面以确保安全。我想知道这是否可能是 Word 格式问题,尽管我尝试使用两个 ClearFormatting 调用删除所有格式。

4

1 回答 1

4

如果你想做一个全部替换然后改变

Selection.Find.Execute

Selection.Find.Execute Replace:=wdReplaceAll

如果您只想替换第一个实例而不是全部,请使用它

Selection.Find.ClearFormatting
Selection.Find.Replacement.ClearFormatting
With Selection.Find
    .Text = "Special"
    .Replacement.Text = "Potato"
    .Forward = True
    .Wrap = wdFindContinue
    .Format = False
    .MatchCase = False
    .MatchWholeWord = False
    .MatchWildcards = False
    .MatchSoundsLike = False
    .MatchAllWordForms = False
End With
With Selection
    If .Find.Forward = True Then
        .Collapse Direction:=wdCollapseStart
    Else
        .Collapse Direction:=wdCollapseEnd
    End If
    .Find.Execute Replace:=wdReplaceOne
End With
于 2012-06-13T16:33:56.807 回答