Search This Blog

Tuesday, January 21, 2020

Counting the Instances of a Text String

From Counting the Instances of a Text String:
THIS is the macro code for providing statistics for an entire Word document:

Sub CountString()
Dim MyDoc As String
Dim txt As String
Dim 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


Note the comment in the above post:

I couldn't get this to work in my version of Word. It would only give me stats for the whole document, not my selection. I am using Word 2016.
To get it to work properly, I just changed
MyDoc = ActiveDocument.Range.Text
to
MyDoc = Selection.Text

THIS is the macro code for providing statistics for selected text within a Word document:

Sub CountString()
Dim MyDoc As String
Dim txt As String
Dim t As String

MyDoc = Selection.Text
txt = InputBox("Text to find")
t = Replace(MyDoc, txt, "")
MsgBox (Len(MyDoc) - Len(t)) / Len(txt) & " occurrences of " & txt
End Sub

No comments: