Log in

View Full Version : Solved: end of document



wax_village
11-13-2008, 04:14 PM
Dear Friends,

I would like to do something like this


Sub macro()

Do Until ThisDocument.Selection.EndOfDocument(True)

Application.Run MacroName:="AnotherMacro"

Loop

End Sub


I tried many similar things some of which loop "AnotherMacro", but forever. Of course, the only way to stop it would be closing the document!!

So, how can I force it to stop once the document ends?

Thanks in advance,
Mina

TonyJollans
11-13-2008, 04:34 PM
I swear we've seen something very similar to this before. To answer with any degree of certainty requires some idea of what "AnotherMacro" is doing. You may want to consider something along the lines of Selection.End = Document.End

fumei
11-14-2008, 10:41 AM
Yes, it would help if we knew what the other macro (procedure) is doing. It is quite possible that a loop through to the end of the document can be built into THAT procedure.

In any case, here is a demo. The document has the following text.

The quick brown fox jumps over the lazy dog. The quick brown fox jumps over the lazy dog. The quick brown fox jumps over the lazy dog. The quick brown fox jumps over the lazy dog. The quick brown fox jumps over the lazy dog.

There are five instances of the word "fox".

You fire the macro "KeepOnGoing" by clicking "Keep On Going" on the top toolbar. As you can see, each iteration of the loop does indeed fire AnotherMacro.

Option Explicit
Public j As Long

Sub AnotherMacro()
MsgBox "Executing the AnotherMacro procedure. " & _
vbCrLf & vbCrLf & "Current counter is: " & j
End Sub


Sub KeepOnGoing()
Dim r As Range
Set r = ActiveDocument.Range
j = 1
With r.Find
Do While .Execute(Findtext:="fox", _
Forward:=True) = True
Application.Run MacroName:="AnotherMacro"
j = j + 1
Loop
End With
End Sub
The procedure KeepOnGoing will execute until there is no more "fox" found. In reality, this means it DOES process to the end of the document. How this may be altered to fit what you are trying to do depends on what you are, in fact, trying to do. Which we do not know.

wax_village
11-15-2008, 03:49 PM
So helpful! Many thanks, Fumei.


:thumb