简单的Word VBA替换宏

时间:2012-06-13 16:24:09

标签: vba ms-word

我正在尝试搜索Word文档并使用指定值替换特定字符串(使用“特殊”的硬编码值)。该宏清楚地表明它在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调用删除所有格式。

1 个答案:

答案 0 :(得分: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