Listing A Macro That Displays the Lengths of Sentences in the Active Document

Sub DisplaySentenceLengths() Dim s As Range Dim maxWords As Integer Dim i As Integer

Dim sentenceLengths() As Integer Dim str As String

With ActiveDocument

' Run through all the sentences to find the longest maxWords = 0

For Each s In .Sentences

If CountWord(s) > maxWords Then maxWords = CountWord(s) End If Next s

1 Redimension the array of sentence lengths

ReDim sentenceLengths(maxWords)

' Run through the sentences again to count 1 the number of sentences for each length

For Each s In .Sentences

' Get the word count for the sentence j = CountWords(s)

1 If it's not empty, add it to the array

If j > 0 Then sentenceLengths(j - 1) = sentenceLengths(j - 1) + 1 End If Next 's

' Construct the string that displays the sentence lengths ' and their frequencies str = "Sentence Length:" & vbTab & "Frequency:" & vbCrLf & vbCrLf

1 The UBound() function tells you the upper bound of an array. ' In this case, it tells you the largest value in sentenceLengths.

For i = 0 To UBound(sentenceLengths) - 1

' Build the string str = str & IIf(i + 1 < 10, " ", "") & i + 1 & _ IIf(i = 0, " word: ", " words: ") & _ vbTab & vbTab & sentenceLengths(i) & vbCrLf

Next 'i

' Display the string

MsgBox str End With End Sub

Using the ActiveDocument object, the macro makes a first pass through all the sentences to find the one with the most words. Notice that the procedure uses the CountWords function from Listing 7.8 to get accurate word counts for each Sentence object. The macro then uses this maximum word count to redimension the sentenceLengths array, which is used to hold the number of occurrences of each sentence length within the document. To calculate these frequencies, the macro then runs through all the sentences again and increments the array values for each length. The macro finishes by constructing and then displaying a string that holds the sentence lengths and frequencies. Figure 7.2 shows an example.

Figure 7.2

The Display Sentence Lengths macro displays a message box such as this to show you the document's sentence lengths and the frequency with which each length occurs.

Microsoft Word 1^1

Sentence Length Frequency;

1 ward:

0

2 wards

0

3 wards

0

4 wards:

0

5 wards:

0

6 wards

7

7 wards

6

8 wards

6

Awards

5

10 wards

6

11 wards

11

12 wards:

7

13 wards

6

14 wards

0

15 wards

4

15 wards

5

17 words:

2

18 wards

6

19 wards

^ To display word count data for each paragraph,replace .Sentencesin Listing 7.2 with .Paragraphs.

0 0

Post a comment