Word VBA查找并继续

时间:2018-08-26 23:31:37

标签: ms-word word-vba find-replace

这是我的问题, 我正在寻找":"并使用VBA键入HTML代码。下面的代码一直在相同的":"处循环,并且不会继续进行下一个,因为我实际上并未删除它。有什么建议吗?

Dim bFound As Boolean


bFound = True
Set r = ActiveDocument.Content

r.Find.ClearFormatting
Do While bFound
    With r.Find
        .Text = ":"
        .Replacement.Text = ":</b>"
        .Forward = True
        .Wrap = wdFindContinue
        .Format = False
        .MatchCase = True
        .MatchWholeWord = False
        .MatchWildcards = False
        .MatchSoundsLike = False
        .MatchAllWordForms = False
        bFound = .Execute(Replace:=wdReplaceOne, Forward:=True)
    End With

    If bFound Then
        r.Select
        Selection.HomeKey Unit:=wdLine
        Selection.TypeText Text:="<b>"
        Selection.EndKey Unit:=wdLine
        Selection.MoveRight
    End If
Loop

1 个答案:

答案 0 :(得分:1)

代码有两个问题,否则会很好:

  1. 它对wdFindContinue属性使用Wrap,这意味着Find将在文档的开头重新开始。根据经验,请始终在代码中使用wdFindStop

  2. 如果要搜索的范围保留在文档中,则必须将找到的范围移动到该点之外。这可以通过使用Range.Collapse来完成。可以将其想象为当您进行选择时按下键盘上的右箭头键:它将光标置于所选内容的正上方。

我已经通过这两个更改修改了原始代码,并且还声明了Range变量。原始代码在没有此声明的情况下运行,表明Option Explicit可能不在代码模块的顶部。如果有的话会更好...

Sub JumpBeyondFound()
    Dim r As Word.Range
    Dim bFound As Boolean

    bFound = True
    Set r = ActiveDocument.content

    r.Find.ClearFormatting
    Do While bFound
        With r.Find
            .Text = ":"
            .Replacement.Text = ":</b>"
            .Forward = True
            .wrap = wdFindStop
            .Format = False
            .MatchCase = True
            .MatchWholeWord = False
            .MatchWildcards = False
            .MatchSoundsLike = False
            .MatchAllWordForms = False
            bFound = .Execute(Replace:=wdReplaceOne, Forward:=True)
        End With

        If bFound Then
            r.Select
            Selection.HomeKey Unit:=wdLine
            Selection.TypeText Text:="<b>"
            Selection.EndKey Unit:=wdLine
            Selection.MoveRight
            r.Collapse wdCollapseEnd
        End If
    Loop
End Sub