找到word文档末尾时如何停止循环?

How to stop a loop when the end of a word document is found?

我有一个逐字验证活动文档的宏。如果 Active Document 中的某个词在“术语圣经”中列出,则宏会向 Active Document 添加注释,并建议用更好的词替换该词。示例:Term=“他是”,Suggestion=“他是”。圣经包含一个 table 有 600 个术语,每行一个术语。第 1 列 = 术语,第 2 列 = 建议)。我的代码循环遍历圣经中的 600 个术语。这是低效的,因为如果我正在验证的文档只有一个词,循环仍然 运行s 600 次。当我正在验证的文档结束时,如何停止代码?或者,如果文档什么都没有,甚至 运行 也不处理。

Dim BibleCounter as Integer
Dim MaxWordsInBible as Integer
MaxWordsToValidate = (ActiveDocument.Words.Count - 1)  'Count words in doc to validate
MaxWordsInBible = Documents(MatrixDocNum).Tables(1).Rows.Count  'Count rows in bible
For BibleCounter = 2 To MaxWordsInBible  'Currently loops 600 times 
   Set findRange = ActiveDocument.range  'Activedocument I'm validating against Bible 
   With findRange.Find
                     .Text = BibleFile.Tables(1).Rows(BibleCounter).Cells(1).range.Text                       
                     .MatchWholeWord = False
                     .Wrap = wdFindStop  'stops find at the end of the document
'Loop to find the suggestion to replace a word in the activedocument with a term in the Bible
                     Do While .Execute(Forward:=True) = True
                        suggestion =  BibleFile.Tables(1).Rows(BibleCounter).Cells(2).range.Text
                        ActiveDocument.Comments.Add findRange, Text:=suggestion
                        findRange.Collapse wdCollapseEnd    'to avoid endless loop
                     Loop   'do while
   End With 'findRange.Find
Next BibleCounter

我确信有多种解决方案。我的解决方案是使用 inrange (pesudocode);

dim searchRange as Range = activeDocument.content
Dim findRange as range = searchRange.duplicate 

findRange.find.execute

Do

     If findRange.find.found andalso findRange.inrange(searchRange) then

           ‘ do processing

       End if

       findrange.collapse (end)
 
       findRange.find.execute
  
While  findrange.find.found
  

您可以通过禁用 ScreenUpdating 来加快速度。代码也可以有所改进,特别是关于如何检索 table 文本:

Application.ScreenUpdating = False
Dim BibleFile As Document, Tbl As Table
Set BibleFile = "some document"
Set Tbl = BibleFile.Tables(1)
For BibleCounter = 2 To Tbl.Rows.Count  'Currently loops 600 times
  With ActiveDocument.Range  'Activedocument I'm validating against Bible
    With .Find
      .Text = Split(Tbl.Cell(BibleCounter, 1).Range.Text, vbCr)(0)
      .MatchWholeWord = False
      .Forward = True
      .Wrap = wdFindStop  'stops find at the end of the document
      'Loop to find the suggestion to replace a word in the activedocument with a term in the Bible
      .Execute
    End With
    Do While .Find.Found = True
      .Comments.Add Range:=.Duplicate, Text:=Split(Tbl.Cell(BibleCounter, 2).Range.Text, vbCr)(0)
      .Collapse wdCollapseEnd    'to avoid endless loop
      .Find.Execute
    Loop
   End With
Next
Application.ScreenUpdating = True

遍历整个 table 不太可能为未找到的表达式增加很多时间 - 它正在处理所有可能会消耗大部分时间的找到的表达式。

当然,如果文档只有几个字,你应该考虑逆向过程,并使用该文档作为来源来检查你的 BibleFile。