RE: Why is cycling in my code? by JeanGuyMarcil
JeanGuyMarcil
Fri Jul 18 05:24:02 PDT 2008
"avkokin" wrote:
> Hello.
> I need to find all words (only upper case) from text and do some list
> of found words. I'm used my macro, bot it had cycled. I can't found my
> wrong. Please give me any tips. Thank you. That my code:
> Sub UcaseList()
> Dim wu As Word.Range
> Dim myArr() As String
> Dim i As Long
>
> With Selection
> .EndKey wdStory
> .TypeParagraph
> End With
>
> For Each wu In ActiveDocument.Words
> If wu.Case = wdUpperCase Then
> myArr = Split(wu)
> Selection.InsertAfter myArr(i) & vbCr
> End If
> Next wu
> End Sub
A few problems with your code:
1) Split creates a one-dimensional array by separating sub-strings using a
delimiter. If no delimiter is used in the function (as in your case) the
space character is assumed to be the delimiter. In your code, "wu" always
returns a single word, usually followed by a space, so "myArr = Split(wu)"
always means that myArr only contains exactly the same a "wu", minus the
space if there was one...
2) Becasue of the 1), "i" is always 0
3) These two considerations are minor. This next one is not! "For Each wu In
ActiveDocument.Words" cycles through all woprds in the current document.
Then, "Selection.InsertAfter myArr(i) & vbCr" keeps inserting words at the
end of the document... You see the problem... Your code keeps finding new
words because your code keeps adding words to the document...
Try this: (No array is used becasue I have no idea why you want to use an
array...)
Sub UcaseList()
Dim rngDoc As Word.Range
Dim wu As Word.Range
Dim lngDocEnd As Long
Set rngDoc = ActiveDocument.Range
lngDocEnd = rngDoc.End
For Each wu In rngDoc.Words
If wu.Case = wdUpperCase Then
ActiveDocument.Range.InsertAfter vbCrLf & wu.Text
rngDoc.End = lngDocEnd
End If
Next wu
End Sub