Looping backwards through a 'For Each' collection

J
John Borton 👤 Member for 7 years 10 months

 

Here is the usual VBA code for looping through all tasks in a project:

  For Each t In ActiveProject.Task

      {code for desired action}

  Next t

This loops through from the top down (as far as I can tell).

Anyone have an ideas as to how I can reverse this and go from the bottom up?

Thanks

JB

 

J
John Borton 👤 Member for 7 years 10 months

// "In "general use," one can't reliably presume a correlation between the ID sequence and the logical sequence." //



Understood.  In this case it's a factory production schedule that by fiat gets used in a particular format over and over so I have pretty tight control on how it's sorted.



Thanks again.



JB

T
Tom Boyle 👤 Member for 19 years 8 months

John,

Glad you got it sorted. 

In "general use," one can't reliably presume a correlation between the ID sequence and the logical sequence.  Still, as you've explained, this certainly seems to offer a bit of streamlining for that particular (ZFF) issue.

Rgds, t 

J
John Borton 👤 Member for 7 years 10 months

That's it Tom ... THANKS.



The task.count property was the secret and this link didn't list it for whatever reason:

https://docs.microsoft.com/en-us/office/vba/api/project.task



A
s to its usage, I actually just successfully used it to modify your ZFFImpose function.  I've been creating schedules with tasks such that I needed to loop through multiple times to get all the float out of all the faux-ZFF relationships (programatically constraining one task simply moved the float up to the previous task requiring another run through). 



My previous schedule had a known number of these relationship layers (3) so I just looped through your code three times.  Now I have a schedule that the users might add an unknown number and I needed a more elegant solution than my previous clutz.



Going through backwards allows your code to now remove the float as far up the chain as needed in one go-round.



I'm a programming hack, so you might have come up with a cleaner solution, but this works slick as a whistle as written.



THANKS (for both the original code AND the mod)

JB

 

T
Tom Boyle 👤 Member for 19 years 8 months

Hi John,  this will do what you ask, though I can think of no good general-use case.  Good luck, tom

Sub BackTasks()

    Dim t As Task

    Dim i As Long

    For i = ActiveProject.Tasks.Count To 1 Step -1

        Set t = ActiveProject.Tasks(i)

        If Not t Is Nothing Then

            'Your Code Here

        End If

    Next i

End Sub

 

Featured Partner

Top Posters

Zine Eddine
2 posts
Alex Lyaschenko
27 posts
mxsiegel
0 posts
Mattvtek
0 posts
Gareth Evans
3 posts
PP Admin
3, 129 posts
Rajkamal Tangirala
5 posts
Rahul Kumar
1 posts
blake333_
0 posts
Jeamiell Ostrovsky
2 posts