PDA

View Full Version : Listing the first words of each sentence in a MsgBox?



Jake Johnson
08-10-2012, 08:56 PM
My first post, here.

I'm trying to do something in Word VBA that seems as though it should be simple, but I can't get it to work:

I just want Word to list all of the first words of each sentence in the open document in a message box, in their original order. This code seems sensible to me, but it doesn't work:

Sub ListFirstWordsOfEachSentenceInMessageBox()

With ActiveDocument.Sentences
MsgBox Words(1)
End With

End Sub


Apparently I have to Dim a range, but doing so doesn't help.
This is code that lists the the first word of each sentence, but with a separate, new message box appearing when the sentence exceeds a given length:

Sub FindLongSentenes()
'This lists the fist word of each sentence in a new msg box.
Dim asentence As Range
For Each asentence In ActiveDocument.Range.Sentences
If asentence.Words.Count > 10 Then
MsgBox asentence.Words(1)
End If
Next

End Sub

The trouble is with the "For each" statement, which produces the new MsgBox.

I'm lost. Do I need to set an array, have VBA paste the results into the array, and then display the array in the MsgBox?

Thanks for any suggestions.

gmaxey
08-10-2012, 09:42 PM
Sub FindLongSentenes()
'This lists the fist word of each sentence in a new msg box.
Dim asentence As Range
Dim str As String
For Each asentence In ActiveDocument.Range.Sentences
If asentence.Words.Count > 10 Then
str = str & asentence.Words(1)
End If
Next
MsgBox str
End Sub

Jake Johnson
08-11-2012, 10:10 AM
Thanks very much. In the version below, I've corrected my spelling errors and added a hard return so that the list is displayed in a column in the message box:


Sub FindStartOfLongSentenes()
'This lists the first word of each sentence in a msg box.

Dim asentence As Range
Dim str As String
For Each asentence In ActiveDocument.Range.Sentences
If asentence.Words.Count > 10 Then
str = str & asentence.Words(1) & vbCrLf
End If
Next
MsgBox str
End Sub