Results 1 to 9 of 9

Thread: Solved: How to count occurences of a string in a doc?

Threaded View

Previous Post Previous Post   Next Post Next Post
  1. #2
    VBAX Expert
    Joined
    Aug 2007
    Location
    Windermere, FL, a 'burb in the greater Orlando metro area.
    Posts
    567
    Location
    Here is a solution to my counting question that works better, based on work by Malcolm (mdmackillop) in the [thread=http://vbaexpress.com/forum/showthread.php?t=21214]Excel forum[/thread] and an assist he got from here.
    Sub CountSpecificStringInWordDoc2()
        Dim txt As String, Lgth As Long, Strt As Long
        Dim i As Long
        Dim oRng As Range
        Dim Tgt As String
        Dim arr()
        ReDim arr(10)
        Dim response As Long
    'Set parameters
        txt = InputBox("String to find")
        Lgth = InputBox("Length of string to return")
        Strt = Len(txt)
    'Return data to array
        With Selection
       .HomeKey unit:=wdStory
          With .Find
             .ClearFormatting
             .Forward = True
             .Text = txt
             .Execute
             While .Found
             arr(1) = arr(1) + 1
             Set oRng = ActiveDocument.Range _
             (Start:=Selection.Range.Start + Strt, _
             End:=Selection.Range.End + Lgth)
             oRng.Start = oRng.End
             .Execute
             Wend
          End With
        End With
    response = MsgBox("I found: " & Str(arr(1)) & " instances of the string: " & txt & _
                    vbCrLf & " in the document: " & ActiveDocument.Name, vbOKOnly, "Number of occurences")
    End Sub
    I'm still curious to know if there is a more elegant way to get the count of the number of occurences of a string in a Word doc.

    Thanks!
    Last edited by Aussiebear; 03-19-2023 at 04:20 PM. Reason: Updated code tags
    Ron
    Windermere, FL

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •