2016-01-28 44 views
0

我有一个程序,它突出显示开始点和结束点之间的所有单词,并循环遍历解压缩以找到相同的条件。程序运行良好,但不停止循环。我不得不中断正在运行的程序来停止它。有人可以帮我写一个条件,说明是否达到了结束条件,并且开始和结束条件不存在,停止程序。我需要为我的程序创建一个停止条件

Sub SomeSub1() 

Dim StartWord As String, EndWord As String 
Dim Find1stRange As range, FindEndRange As range 
Dim DelRange As range, DelStartRange As range, DelEndRange As range 

Application.ScreenUpdating = False 
Application.DisplayAlerts = False 
'Setting up the Ranges 
Set Find1stRange = ActiveDocument.range 
Set FindEndRange = ActiveDocument.range 
Set DelRange = ActiveDocument.range 

'Set your Start and End Find words here to cleanup the script 
StartWord = "From: Yussuf Ismail" 
EndWord = "Kind regards" 

'Starting the Find First Word 
With Find1stRange.Find 
    .Text = StartWord 
    .Replacement.Text = "" 
    .Forward = True 
    .Wrap = wdFindAsk 
    .Format = False 
    .MatchCase = False 
    .MatchWholeWord = False 
    .MatchWildcards = False 
    .MatchSoundsLike = False 
    .MatchAllWordForms = False 

    'Execute the Find 
    Do While .Execute 
     'If Found then do extra script 
     If .Found = True Then 
      'Setting the Found range to the DelStartRange 
      Set DelStartRange = Find1stRange 
      'Having these Selections during testing is benificial to test your script 
      DelStartRange.Select 

      'Setting the FindEndRange up for the remainder of the document form the end of the StartWord 
      FindEndRange.Start = DelStartRange.End 
      FindEndRange.End = ActiveDocument.Content.End 

      'Having these Selections during testing is benificial to test your script 
      FindEndRange.Select 


      'Setting the Find to look for the End Word 
      With FindEndRange.Find 
       .Text = EndWord 
       .Execute 

       'If Found then do extra script 
       If .Found = True Then 
        'Setting the Found range to the DelEndRange 
        Set DelEndRange = FindEndRange 

        'Having these Selections during testing is benificial to test your script 
        DelEndRange.Select 

       End If 

      End With 

      'Selecting the delete range 
      DelRange.Start = DelStartRange.Start 
      DelRange.End = DelEndRange.End 
      'Having these Selections during testing is benificial to test your script 
      DelRange.Select 
DelRange.HighlightColorIndex = wdPink 
      'Remove comment to actually delete 




     End If  'Ending the If Find1stRange .Found = True 
    Loop  'Ending the Do While .Execute Loop 
End With 'Ending the Find1stRange.Find With Statement 


End Sub 
+0

我建议您使用布尔变量来追踪.Execute是否成功。实际上,“Do”正在测试原始的.Execute,而不是在循环中执行的那个。如果您测试每次应该帮助时设置为.Execute的布尔值。如果.Found - 使用相同的布尔变量,那更可靠。 –

+0

好的一段代码@jaydub(哈哈以为它看起来很熟悉)。 –

回答

0

它使要去由于Application.DisplayAlerts = False

这将删除“搜索已到达文档的末尾。是否要继续在开始搜索?”信息。

如果您删除Application.DisplayAlerts = False,那么它将在文档结束时停止,并且该消息将弹出。

而且更改初始Find如下:

.Wrap = wdFindAsk 

.Wrap = wdFindStop 

这不会再去问这个问题,只是停止Find

相关问题