Log in

View Full Version : Performance issues looping through collection



debkev1010
07-14-2023, 06:34 AM
Hi,
I have some code in which I run against a Word compare (redlines created by Word's Compare/Combine function) document. Some of the redlines Word makes aren't true redlines and I'd like to Reject these redlines to clean-up the document. I've setup a For Each loop to go through the Revisions collection looking for pairs of Insert/Delete. The script takes less than 30 seconds when I have this simple loop below:


Set xRevisions = worddoc.Revisions
For Each xRev in xRevisions
xRev.Range.Select
Next

When I add the following 'if' statement inside the loop to compare the current Revision with the next Revision, the script takes 30 minutes to run:

If xRevisions.Item(xRev.Index).Range.Fields.Count <> 0 or xRevisions.Item(xRev.Index + 1).Range.Fields.Count <> 0 Then
x = x
End If

Is there a faster way to handle this? Seems like a huge difference.

Thanks,
Kevin

Aussiebear
07-14-2023, 11:30 AM
debkev1010, Please wrap your code with tags when submitting code to the forum. This will improve readability for others. Have a look at my signature for the method.

tonyadams
08-16-2023, 02:52 AM
Instead of directly using the `Range.Fields.Count` method within the loop, you can store the field count values in variables before the loop begins. This way, you avoid repeated method calls for each iteration. fnf (https://fnf2.io/)

Set xRevisions = worddoc.RevisionsFor Each xRev in xRevisions
currentFieldCount = xRevisions.Item(xRev.Index).Range.Fields.Count
nextFieldCount = xRevisions.Item(xRev.Index + 1).Range.Fields.Count
If currentFieldCount <> 0 Or nextFieldCount <> 0 Then
' Your logic here
End If
Next