PDA

View Full Version : Different Nested Loops



balumail75
08-25-2011, 07:19 AM
Hello,

Please clarify how the different nested loops work with examples.

Eg., For Loop (i = 1 to Slidescount)
For Loop (j=1 to shapescount)
For Each Shape
if condition then
endif
next Shape
Next
Next

It will very usefull for me with an example clarification.

Thanks,

Regards,
Balu.

Paul_Hossler
08-25-2011, 05:46 PM
The online help for For/Next and For Each/Next is pretty good and has examples.

This just loops 10 times


For i = 1 to 10
Msgbox i
Next i



Some objects are part of a collection, and you can use


For Each oSlide in ActivePresentation.Slides
Msgbox oSlide.Name
Next


to go throught each slide in the Slides collection in the ActivePresentation


You can also use the index for objects that are members of a collection


For i = 1 to ActivePresentation.Slides.Count
Msgbox ActivePresentation.Slides(i).Name
Next



If you were going to delete a specific shape on a slide, you should start to the highest number and decrease the loop varialbe


For Each oSlide in ActivePresentation.Slides
For i = oSlide.Shapes.Count to 1 Step -1
If oSlide.Shapes(i).Name = "ABC" Then
oSlide.Shapes(i).Delete
EndIf
Next i
Next


Paul

John Wilson
08-28-2011, 03:18 AM
Another loop which can be useful is the Do >> Until loop

The loop runs until a condition is met and could be used to make a very simple timer.

Sub Time_Me()
Dim endtime As Single
endtime = Timer + 10 ' ten seconds
Do
Loop Until Timer > endtime
MsgBox "Done"
End Sub
Words of caution

Make sure the condition WILL be met or the loop will go on for ever!
Your PC holds a constant "Timer" which is a SINGLE type in elapsed fractions of seconds. This resets to zero every Midnight. In the unlikey event your timer runs over Midnight you will have problems.

There is a similar loop While this is true Wend. You can use this if you have a loop that may never run. The Do Until loop above will always run once. You can also say Do Until this condition>> Loop