View Single Post
 
Old 12-20-2020, 02:06 PM
gmaxey gmaxey is offline Windows 10 Office 2016
Expert
 
Join Date: May 2010
Location: Brasstown, NC
Posts: 1,617
gmaxey is just really nicegmaxey is just really nicegmaxey is just really nicegmaxey is just really nicegmaxey is just really nice
Default

Chopper,

You don't have to replace text if you find it. You just want to do something with that text when found. I think eduzs point, and mine, to find the text wherever it is in the thousands of paragraphs and process it. For example, I created as document with 10,000 paragraphs of similar text then I went in and added "XXX" to about a dozen or so.

See these examples:

Code:
Sub Example1()
'Burtally slow. Will probably lock up Word.
Dim oPar As Paragraph
Dim lngIndex As Long
Dim lngCount As Long
  For lngIndex = 1 To ActiveDocument.Paragraphs.Count
    Set oPar = ActiveDocument.Paragraphs(lngIndex)
    If InStr(oPar.Range.Text, "XXX") > 0 Then
      lngCount = lngCount + 1
      DoEvents
      'Do something with found text
    End If
  Next
  MsgBox lngCount
lbl_Exit:
  Exit Sub
End Sub

Sub Example2()
'Faster but still slow
Dim oPar As Paragraph
Dim lngCount As Long
  For Each oPar In ActiveDocument.Paragraphs
    If InStr(oPar.Range.Text, "XXX") > 0 Then
      lngCount = lngCount + 1
      DoEvents
      'Do something with found text
    End If
  Next
  MsgBox lngCount
lbl_Exit:
  Exit Sub
End Sub

Sub Example3()
'Even faster
Dim oPar As Paragraph
Dim lngCount As Long
  Set oPar = ActiveDocument.Paragraphs(1)
  Do
    If InStr(oPar.Range.Text, "XXX") > 0 Then
      lngCount = lngCount + 1
      'Do something with found text
    End If
    Set oPar = oPar.Next
  Loop Until oPar.Range.End = ActiveDocument.Range.End
  MsgBox lngCount
End Sub

Sub Example4()
'Likely faster yet because we only look a the paragraphs containing the text to find.
Dim oRng As Range
Dim oPar As Paragraph
Dim lngCount As Long
  Set oRng = ActiveDocument.Range
  With oRng.Find
    .Text = "XXX"
    While .Execute
      lngCount = lngCount + 1
      'Do something with found text
      oRng.Collapse wdCollapseEnd
    Wend
  End With
  MsgBox lngCount
End Sub
__________________
Greg Maxey
Please visit my web site at http://www.gregmaxey.com/
Reply With Quote