Do Until ... loop - endlessly

G

G Teachman

Hello,

I have code in a macro that finds something, makes a copy of it, goes to
another document, pastes the selection, returns to the original document.
This works, but I need to do it an unknown number of times in different
documents. So, I tried the following (based on reading a lot in this group).

Do Until ActiveDocument.Bookmarks("\Sel") =
ActiveDocument.Bookmarks("\EndOfDoc")
stuff gets done in here
Loop

The active document does have an EndOfDoc bookmark. (As an aside, I don't
know what the ("\Sel") is for.) The result is an endless loop. It finishes
the document and starts over again. I have to CntlBreak to stop it.

I also tried a suggestion I found here by adding .End in two places. As
seen here.

Do Until ActiveDocument.Bookmarks("\Sel").End =
ActiveDocument.Bookmarks("\EndOfDoc").End

This results in the same behavior as the first try.

Why is the bookmark not being found/recognized and the loop ended?

Thanks,
 
F

Fumei2 via OfficeKB.com

1. Please post more detailed code.

2. It is very likely you do not have to use the EndOfDoc bookmark at all.

3. It is for certain that you likely do NOT have to use Selection, nor use
Copy and Paste actions.

4. It is good to use Document objects.

For example:
Sub CopyStuff()
Dim r As Range
Dim ThisDoc As Document
Dim ThatDoc As Document

Set ThisDoc = ActiveDocument
Set r = ThisDoc.Range
Set ThatDoc = Documents.Add

With r.Find
Do While .Execute(FindText:="excellent", _
Forward:=True) = True
r.Expand Unit:=wdSentence
ThatDoc.Range.InsertAfter r.Text & vbCrLf
r.Collapse 0
Loop
End With
End Sub

The above:

1. makes a document object of the source document (the one containing the
search string)
2. makes a Range object of that document
3. makes a document object of a NEW document

NOTE: this is now the ActiveDocument. Because the code uses document
OBJECTS, there is no need to switch back and forth, or copy and paste.
Because the range object is Set, you can work with it even though the
originating document (ThisDoc) is NOT the activedocument.

4. using .Find of the range object (the contents of ThisDoc), search for
"excellent"
5. if found, expand the range to the Sentence
6. insert that text at the end of the new document range

The code will go through the entire first document, to the end.

Say:

This is some excellent suishi. Followed by a different sentence.
This sentence does not have the search word.
And wow, this sake is excellent.


The new document (ThatDoc) will have:

This is some excellent suishi.
And wow, this sake is excellent.
 

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