Hi Mike,
Admittedly this is not intuitive at all. What Word considers a 'word'
isn't the usual definition. Each member of the Words collection
includes all the spaces that follow the word. It may also be a series
of punctuation characters. Most important in this discussion, it may
also be a sequence of space characters at the beginning of a document,
up to but not including the first nonspace character.
In the VBA editor, right-click aWord and choose Add to Watch. Now use
F8 to single-step your macro. After the first StrReverse call, the
space that used to follow the first word is now at the beginning of
the document. On the next time through the loop, aWord consists of the
range of just that single space character (you can check its Start and
End to see that they're 0 and 1, respectively). Then StrReverse just
'reverses' that space again and again in an infinite loop. (Tip: to
break out of the loop, press Ctrl+Break.)
An unintuitive thing about this is that the For Each recomputes the
location of the 'next word' on each iteration, starting from the Start
of the document. This is not like a standard For loop, which fixes the
test condition during the first iteration and never again.
A workaround is to use a For loop that counts backward through the
Words collection. In addition, you need some code to move the space
character from its new position at the beginning of the word to its
old position, to prevent all the nonspace characters from being jammed
together. Try this version:
Sub TestReverseWords2()
Dim myRange As Range
Dim aWord As Range
Dim nCount As Long
Set myRange = ActiveDocument.Range(Start:=0, End:=Selection.End)
For nCount = myRange.Words.Count To 1 Step -1
Set aWord = myRange.Words(nCount)
aWord.Text = StrReverse(aWord.Text)
If (aWord.Characters.First = " ") Then
aWord.Text = Mid$(aWord.Text, 2) & " "
End If
Next nCount
End Sub