Results 1 to 5 of 5

Thread: Output of Number of Hits in a Search Macro

Threaded View

Previous Post Previous Post   Next Post Next Post
  1. #4
    Microsoft Word MVP 2003-2009 VBAX Guru gmaxey's Avatar
    Joined
    Sep 2005
    Posts
    3,411
    Location
    Quote Originally Posted by R. Racoon View Post
    Using Ctrl-F in a Word document opens a new search box, that will show each of the hits for an entered keyword. It also lists X results, where X = the number of hits.
    My question is: What code can be used to capture that X quantity in a VBA macro, in order to inform the user how many results were found for a search macro?
    Sub Test()
        MsgBox CountWordOccurrences("Test")
    End Sub
    
    Function CountWordOccurrences(strText)
        Dim lngIndex As Long
        Dim oRng As Range
        Set oRng = ActiveDocument.Range
        With oRng.Find
            .Text = strText
            .MatchCase = False
            .Forward = True
            .Wrap = wdFindStop
            While .Execute
                lngIndex = lngIndex + 1
                oRng.Collapse wdCollapseEnd
            Wend
            CountWordOccurrences = lngIndex
        End With
        lbl_Exit:
        Exit Function
    End Function
    Last edited by Aussiebear; 01-28-2025 at 03:15 PM.
    Greg

    Visit my website: http://gregmaxey.com

Posting Permissions

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