Consulting

Results 1 to 9 of 9

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

  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

  2. #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

  3. #3
    Administrator
    VP-Knowledge Base
    VBAX Grand Master mdmackillop's Avatar
    Joined
    May 2004
    Location
    Scotland
    Posts
    14,489
    Location
    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.
    How about using Find/Replace? Find "Text" Replace "^&"
    See here and here
    MVP (Excel 2008-2010)

    Post a workbook with sample data and layout if you want a quicker solution.


    To help indent your macros try Smart Indent

    Please remember to mark threads 'Solved'

  4. #4
    Administrator
    VP-Knowledge Base VBAX Grand Master mdmackillop's Avatar
    Joined
    May 2004
    Location
    Scotland
    Posts
    14,489
    Location
    I came across this methodology. It will count strings, but also as part of words.
     
    Option Compare Text
    Sub CountOccurences()
        Dim MyDoc As String, txt As String, t As String
    MyDoc = ActiveDocument.Range.Text
    txt = InputBox("Text to find")
        t = Replace(MyDoc, txt, "")
        MsgBox (Len(MyDoc) - Len(t)) / Len(txt) & " occurrences of " & txt
    End Sub
    Last edited by Aussiebear; 03-19-2023 at 04:21 PM. Reason: Updated code tags
    MVP (Excel 2008-2010)

    Post a workbook with sample data and layout if you want a quicker solution.


    To help indent your macros try Smart Indent

    Please remember to mark threads 'Solved'

  5. #5
    VBAX Expert
    Joined
    Feb 2005
    Posts
    929
    Location
    here is some brute force code that is simplier and seems to work. It does not differentiate between "words" and text string.
        Sub CountWords()
            Dim I           As Long
            Dim J           As Long
            Dim Num         As Long
            Dim TargetText  As String
    TargetText = InputBox("target text?")
            J = 1
            I = 1
            While I > 0
       I = InStr(J, ActiveDocument.Range.Text, TargetText)
       If I > 0 Then
          Num = Num + 1
          J = I + 1
       End If
            Wend
            MsgBox Num
        End Sub
    Last edited by Aussiebear; 03-19-2023 at 04:22 PM. Reason: Updated Code tags
    "It's not just the due date that's important, it's also the do date" [MWE]

    When your problem has been resolved, mark the thread SOLVED by clicking on the Thread Tools dropdown menu at the top of the thread.

  6. #6
    VBAX Wizard
    Joined
    May 2004
    Posts
    6,713
    Location
    Or...

    Dim r As Range
    Dim j As Long
    Set r = ActiveDocument.Range
    With r.Find
       .Text = InputBox("What word(s)?")
       Do While .Execute(Forward:=True) = True
           j = j + 1
        Loop
    End With
    MsgBox "Given word(s) was found " & j & " times."
    No error trapping on the input string. If there is no string found (because of spelling errors for example) the message will be "0 times"
    Last edited by Aussiebear; 03-19-2023 at 04:23 PM. Reason: Updated code tags

  7. #7
    VBAX Newbie
    Joined
    Oct 2008
    Posts
    1
    Location
    Here is a simple way to do it, using the Split() function, where "Needle" is the word/string you want to count:

    Dim Haystack As String
    Dim Needle As String

    Dim a As Variant

    a = Split(Haystack, Needle)

    MsgBox UBound(a)

  8. #8
    VBAX Expert
    Joined
    Aug 2007
    Location
    Windermere, FL, a 'burb in the greater Orlando metro area.
    Posts
    567
    Location
    Quote Originally Posted by nim81
    Here is a simple way to do it, using the Split() function, where "Needle" is the word/string you want to count:

    Dim Haystack As String
    Dim Needle As String
    Dim a As Variant
    a = Split(Haystack, Needle)
    MsgBox UBound(a)
    Thanks for the suggestion. Not stated in my query is the requirement that the code run on Excel 2004 in Office for Mac where we have no 'split' function.
    Ron
    Windermere, FL

  9. #9
    VBAX Wizard
    Joined
    May 2004
    Posts
    6,713
    Location
    There is no Split() in Excel for the Mac? Ai caramba! Why on earth would it be different for the Mac?

Posting Permissions

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