Search code examples
vbams-wordduplicatesparagraph

How to Identify Paragraph that has a Duplicate?


I'm trying to identify paragraphs (first instance) in a Word document that have a duplicate (second instance).

This code identifies the second instance.

I'm trying to highlight the first instance in a different color.

Sub highdupParagraphs()
  Dim p As Paragraph
  Dim d As New Scripting.Dictionary
  Dim t As Variant
  Dim i As Integer
  Dim StartTime As Single

  StartTime = Timer

  ' collect duplicates
  For Each p In ActiveDocument.Paragraphs
    t = p.Range.Text
    If t <> vbCr Then
      If Not d.Exists(t) Then d.Add t, New Scripting.Dictionary
      d(t).Add d(t).Count + 1, p
    End If
  Next

  ' highlight
  For Each t In d
    For i = 2 To d(t).Count
      d(t)(i).Range.HighlightColorIndex = wdPink
    Next
  Next
  
  Application.ScreenUpdating = True

  MsgBox "This code ran successfully in " & Round(Timer - StartTime, 2) & " seconds", vbInformation
End Sub

Solution

  • In a single loop:

    Sub highdupParagraphs()
        Dim p As Paragraph
        Dim d As New Scripting.Dictionary
        Dim t As Variant, StartTime As Single
        
        StartTime = Timer
        
        For Each p In ActiveDocument.Paragraphs
            t = p.Range.Text
            If t <> vbCr Then
                If Not d.Exists(t) Then
                    d.Add t, p 'store the first instance
                Else
                    If Not d(t) Is Nothing Then
                        'color first instance and unset it
                        d(t).Range.HighlightColorIndex = wdYellow
                        Set d(t) = Nothing
                    End If
                    p.Range.HighlightColorIndex = wdPink
                End If
            End If
        Next
        
        MsgBox "This code ran successfully in " & Round(Timer - StartTime, 2) & " seconds", vbInformation
    End Sub