【问题标题】:Word 2010 VBA Macro: loop to end of documentWord 2010 VBA 宏:循环到文档末尾
【发布时间】:2020-07-07 00:59:29
【问题描述】:

我已经录制了一个简单的宏来查找单词“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  

【问题讨论】:

  • 您遇到的问题是什么?与所有编程一样,请具体说明。
  • “quantity”这个词在文档中重复了不定次数,不知道怎么重复宏,直到文档结束才停止。

标签: vba ms-word


【解决方案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

【讨论】:

    【解决方案2】:

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

    【讨论】:

      猜你喜欢
      • 2016-02-11
      • 2011-12-15
      • 1970-01-01
      • 2012-10-19
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-09-29
      • 2018-07-05
      相关资源
      最近更新 更多