StrReverse() function - infinite loop

M

mike510

I have just started program with Word 2002
While trying to reverse each word in a line of text encountered a
problem: Word enters an infinite loop and stops responding.
Could somebody explain why?
Code:
---------------
Sub TestReverseWords()
Dim myRange As Range
Dim aWord As Object
Set myRange = ActiveDocument.Range(Start:=0, End:=Selection.End)
For Each aWord In myRange.Words
aWord.Text = StrReverse(aWord.Text)
Next aWord
End Sub
 
J

Jay Freedman

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
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top