Consulting

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. #1
    VBAX Expert
    Joined
    Aug 2007
    Location
    Windermere, FL, a 'burb in the greater Orlando metro area.
    Posts
    567
    Location

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

    Hi, All,

    I need some help getting the following shippet of code to count the number of instances of a string in a document. My test document has 4 instances of the string scattered through it, but my code finds none of them because .FOUND is returning False.
    Sub CountAWord()
        Dim intRowCount As Long     ' was integer
        Dim aRange As Range
        Dim response As Long
        intRowCount = 0
        Set aRange = ActiveDocument.Range
        With aRange.Find
            Do
                .Text = "ID3" ' the word I am looking for
    Debug.Print aRange.Find.Text
    Debug.Print ActiveDocument.Name
    Debug.Print .Found
                .Execute
                If .Found Then
                    intRowCount = intRowCount + 1
                End If
            Loop While .Found
        End With
        response = MsgBox("I counted " & Str(intRowCount) & vbCrLf & " in doc: " & ActiveDocument.Name, vbOKOnly, "Number of Instances")
        Set aRange = Nothing
    End Sub
    Is there an easier way, than the above code, to count the number of occurrences of a keyword (or phrase or string) in a document?

    Thanks!
    Last edited by Aussiebear; 03-19-2023 at 04:17 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
  •