vbaselectms-wordrangecomments

VBA in Word - selecting ranges and making comments


I've been trying to figure this out, but no such luck.

Ultimately, I'm trying to create a macro that searches the Word document for each instance of String1, selects a range of text starting with that String1 all the way through the next instance of String2, and then creates a comment for that text. If anyone already has something similar or can push me in the right direction, that'd be most helpful.

(Context: I'm a writer working on a novel, and I have uses for this macro during my editing process.)


Solution

  • Try the following:

    Sub Demo()
    Application.ScreenUpdating = False
    Dim i As Long, StrFnd As String, StrCmnt As String
    StrFnd = ""
    Restart:
    StrFnd = InputBox("What is the Text to Find? Please Input as:" _
        & vbCr & "Start String|End String", , StrFnd)
    If StrFnd = "" Then Exit Sub
    If InStr(StrFnd, "|") = 0 Then
      MsgBox "Invalid Input. Please try again.": GoTo Restart
    End If
    StrFnd = "(" & Split(StrFnd, "|")(0) & ")[!\1]@" & Split(StrFnd, "|")(1)
    StrCmnt = InputBox("What is the Default Comment?")
    With ActiveDocument.Range
      With .Find
        .ClearFormatting
        .Replacement.ClearFormatting
        .Text = StrFnd
        .Replacement.Text = ""
        .Forward = True
        .Wrap = wdFindStop
        .Format = False
        .MatchWildcards = True
      End With
      Do While .Find.Execute
        i = i + 1: .Comments.Add .Duplicate, StrCmnt
        If .End = ActiveDocument.Range.End Then Exit Do
        .Collapse wdCollapseEnd
      Loop
    End With
    Application.ScreenUpdating = True
    MsgBox i & " Comments Added."
    End Sub
    

    Note: The search is case-sensitive.