PDA

View Full Version : Infinite FOR EACH loop when second application opened



Diced
04-08-2022, 08:16 PM
Hi, I am having an issue with a FOR EACH loop that iterates through files in a folder and opens them in word, does a search and replace then closes the doc.
Loop works fine and iterates through all the documents but does not exit once they have all been opened it keeps iterating infinitely.
I have removed the search and replace portion of the below code as it is still an infinate loop with that section commented out. Loop works as it should if WITH statements are commented. Any help would be greatly appreciated.


Set oFileSystem = CreateObject("Scripting.FileSystemObject")
Set oFolder = oFileSystem.GetFolder(FolderN)
MsgBox (oFolder.Files.Count)

For Each oFile In oFolder.Files

DName = oFile.Name

With msWord
.Visible = True
.Documents.Open (FolderN & "\" & DName)
.Activate

With .Activedocument
.Save
.Close
End With


End With

Next oFile

arnelgp
04-08-2022, 11:50 PM
why not save the filenames to collection first:


Set oFileSystem = CreateObject("Scripting.FileSystemObject")
Set oFolder = oFileSystem.GetFolder(FolderN)
MsgBox (oFolder.Files.Count)

'arnelgp
Dim col As New Collection
Dim i as integer


For Each oFile In oFolder.Files
col.Add Item:= FolderN & "\" & oFile.Name, Key:= (col.Count + 1 & "")
Next


Set oFile = Nothing
Set oFolder = Nothing
Set oFileSystem = Nothing

With msWord
For i = 1 to col.Count
.Visible = True
.Documents.Open (col.Item(i))
.Activate


With .Activedocument
.Save
.Close
End With
Next
End With

Diced
04-09-2022, 05:50 PM
Thanks arnelgp i had put in a work around but your solution is much nicer. Thanks.
Still curious why the for each loop restarts in my original code so i can avoid the scenario in the future.

Cheers

Paul_Hossler
04-09-2022, 06:42 PM
Thanks arnelgp Still curious why the for each loop restarts in my original code so i can avoid the scenario in the future.

I'm guessing that each time you saved the file, the loop saw it as new one that it hadn't seen before and tried to process it

That's why capturing the names in a collection first and then processing out of the collection worked

Sort of like a recursive function without an Exit condition test

snb
04-10-2022, 05:03 AM
Sub M_snb()
c00="G:\OF\"
sn=filter(split(createobject("wscript.shell").exec("cmd /c dir " & c00 & "*.doc /b").stdout.readall,vbcrlf),".doc")

for each it in sn
with getobject(c00 & it)
c01 =c01 & vblf & filter(split(.content,vbcr),"searchitem")(0)
.close 0
end with
next
End Sub

You don't need to make a Word document visible to search in it. Without showing each file the code is much faster.
You don't need to save a file in which only some searching has been taken place. It only slows down the code unnecessarily.