John
John

Reputation: 53

Counting words in Word document, including footnores

I periodically receive long documents that include footnotes and am trying to find a way using VBA to count the number of words on each page, including footnotes. It doesn't matter if a footnote spills over onto the next page, I just the word count including footnotes that are anchored on the page.

I have a macro that correctly counts the number of words in the body of the text, using the command:

WordCount = ActiveDocument.Range(Start:=pos1, End:=pos2).ComputeStatistics(wdStatisticWords)

The variables pos1 and pos2 have been set to the first and last characters of the page being counted.

However, when I add the True parameter to ComputeStatistics(wdStatisticWords, True), to IncludeFootnotesAndEndnotes, as in:

WordCount = ActiveDocument.Range(Start:=pos1, End:=pos2).ComputeStatistics(wdStatisticWords, True)

it doesn't work, giving an error that there are too many parameters. It appears that when using a Range, the IncludeFootnotesAndEndnotes parameter is not available.

How do you count the words within footnotes contained in a range?

Upvotes: 1

Views: 890

Answers (1)

Ryan Wildry
Ryan Wildry

Reputation: 5677

I think what you will need to do is iterate into each of the StoryRanges and update a counter. Here is a small example that should serve as an example, however, you will likely need to tweak it for your specific case (review my note about the enum for StoryRanges)

Here's the code:

Public Sub Count_All_Words()
    Dim Story_Ranges         As Variant: Set Story_Ranges = ActiveDocument.StoryRanges
    Dim Story_Range          As Object
    Dim WordCount            As Long

    'Loop through each story range and only include the footer and Main story to the word count
    For Each Story_Range In Story_Ranges
        'You may need to check additional types, lookup the enumerations for StoryType here:
        'https://msdn.microsoft.com/en-us/library/bb238219(v=office.12).aspx
        If Story_Range.StoryType = wdMainTextStory Or Story_Range.StoryType = wdFootnoteSeparatorStory Then
            'Add to the word count
            WordCount = WordCount + Story_Range.ComputeStatistics(wdStatisticWords)
        End If
    Next

    Debug.Print "The word count is: " & WordCount
End Sub

Upvotes: 1

Related Questions