Word VBA:如何通过替换对象仅替换字符串的下一个实例

时间:2015-05-21 18:09:40

标签: vba word-vba

这是一个愚蠢的问题,但无法弄清楚。

直接从Microsoft站点:

此示例查找单词" Start"的每个实例。在活动文档中,用" End替换它。"查找操作忽略格式化但匹配要查找的文本的大小写("开始")。

Set myRange = ActiveDocument.Range(Start:=0, End:=0)
 With myRange.Find
.ClearFormatting
.Text = "Start"
With .Replacement
    .ClearFormatting
    .Text = "End"
End With
.Execute Replace:=wdReplaceAll, _
    Format:=True, MatchCase:=True, _
    MatchWholeWord:=True
End With

我需要知道如何制作它,以便它只找到Start的下一个实例并将其替换为End。这将使整个文档中的所有其他End保持完整。

3 个答案:

答案 0 :(得分:2)

您应该使用wdReplaceOne代替wdReplaceAll

答案 1 :(得分:0)

此讨论提供了一些有用的建议:Replace only last occurrence of match in a string in VBA。简而言之,这是一个从搜索字符串开始循环直到搜索参数的第一个实例所在并仅替换它的情况。

答案 2 :(得分:0)

你应该能够适应这个:

Sub Tester()

    Const FIND_WHAT as String = "Start"
    Const REPLACE_WITH as String = "End"

    Const REPLACE_WHICH As Long = 4 'which instance to replace?

    Dim rng As Range, i As Long

    i = 0
    Set rng = ActiveDocument.Content
    With rng.Find

        .ClearFormatting
        .Text = FIND_WHAT 

        Do While .Execute(Format:=True, MatchCase:=True, _
                           MatchWholeWord:=True)

            i = i + 1
            If i = REPLACE_WHICH Then
                'Note - "rng" is now redefined as the found range
                '  This happens every time Execute returns True
                rng.Text = REPLACE_WITH 
                Exit Do
            End If

        Loop

    End With

End Sub