1
votes

I have a macro which searches for a paragraph break ("^p") in a selection of text. I notice that, in the Advanced Find & Replace Screen, word tells you how many instances of the search item has been found. How do I extract this count?

I have recorded a VBA macro which does the find in a selection, but I don't know how to extract the number of occurrences from that selection. Does anyone know how to do this (would prefer to just extract it from the find&replace function as opposed to writing a for-loop)?

Selection.Find.ClearFormatting
   With Selection.Find
    .Text = "^p"
    .Replacement.Text = ""
    .Forward = True
    .Wrap = wdFindAsk
    .Format = False
    .MatchCase = False
    .MatchWholeWord = False
    .MatchWildcards = False
    .MatchSoundsLike = False
    .MatchAllWordForms = False
End With
1
Has your question been answered? - Cindy Meister

1 Answers

1
votes

You can't - that isn't exposed to the developer, unfortunately!

But you don't necessarily have to loop Word's Find. You can use other functionality which executes faster than the object model to count the number of instances of a string. For example loop Instr to count the number of instances:

Sub TestGetCountOfFoundInstances()
    Dim rng As Word.Range
    Dim searchTerm As String
    Dim nrInstances As Long
    Dim bFound As Boolean

    searchTerm = Chr(13)
    Set rng = Selection.Range
    nrInstances = CountNrInstancesSearchTerm(rng, searchTerm)
    Debug.Print "The term " & searchTerm & " was found " & nrInstances & _
                " times."
    bFound = rng.Find.Execute(findText:="^p", ReplaceWith:="^l", Replace:=wdReplaceAll)
End Sub

Function CountNrInstancesSearchTerm( _
         rng As Word.Range, searchTerm As String) As Long
    Dim counter As Long, loc As Long, startPos As Long
    Dim t As String

    t = rng.Text
    startPos = 1
    Do
        loc = InStr(startPos, t, searchTerm)
        If loc > 0 Then
            counter = counter + 1
            startPos = loc + 1
        End If
    Loop While loc > 0
    CountNrInstancesSearchTerm = counter
End Function