Word 2010 VBA宏:循环到文档结尾

时间:2014-05-29 21:49:53

标签: word-vba

我录制了一个简单的宏来查找单词“Quantity”,转到该行的末尾并插入一个回车符。我需要重复它到文档的末尾并退出,否则我将有一个无限循环。

代码:

     Selection.Find.ClearFormatting
     With Selection.Find
    .Text = "Quantity:"
    .Replacement.Text = ""
    .Forward = True
    .Wrap = wdFindContinue
    .Format = False
    .MatchCase = True
    .MatchWholeWord = False
    .MatchWildcards = False
    .MatchSoundsLike = False
    .MatchAllWordForms = False
End With
Selection.Find.Execute
Selection.EndKey Unit:=wdLine
Selection.TypeParagraph  

2 个答案:

答案 0 :(得分:1)

将代码更改为此,请注意使用wdFindStop。

Selection.Find.ClearFormatting
     With Selection.Find
    .Text = "Quantity:"
    .Replacement.Text = ""
    .Forward = True
    .Wrap = wdFindStop
    .Format = False
    .MatchCase = True
    .MatchWholeWord = False
    .MatchWildcards = False
    .MatchSoundsLike = False
    .MatchAllWordForms = False
End With

do while Selection.Find.Execute = true
   Selection.EndKey Unit:=wdLine
    Selection.TypeParagraph  
loop

如果你有可能失败的文件类型,你可以使用Selection.Start by 像这样替换循环:

Dim lastPos As Long
lastPos = -1
Do While Selection.Find.Execute = True
    If lastPos > Selection.Start Then Exit Do
    Selection.EndKey Unit:=wdLine
    Selection.TypeParagraph
Loop

答案 1 :(得分:0)

在结束后添加Selection.Find.Execute Replace:=wdReplaceAll