For Each In Loop

b. For Each In Loop
For Each In Loop works like For Next Loop but in a different way.
This is usually use in array. This is a little bit complicated topic. But I will just give you a simple example.
What is array?
 It is just a group of objects that are stored.
The following is the syntax For Each In Loop

    For Each ItemInArray In AnArray

         'Do something inside

    Next IteminArray
 
Let's try using an example from previous lesson.




  AnArray = Range("A1:A10")
 Meaning, store the value of range  ("A1:A10") in AnArray Variable.
Those values are: 2,4,6,8,10,11,12,13,14,15,16,17,18,19,20.

For Each IteminArray In AnArray 
   It just means that for each value stored in Array.
   What will I do with each of this value?

MsgBox (IteminArray)
   I will display it in a messagebox.

Try it for yourself and see how.

Homework:
For each sheet in your workbook, rename it to 1,2,3 etc.. in ascending order.

I hope you learn something from For Loop and For Each Loop.

Next tutorial is Do While/Until Loop.



No comments:

Post a Comment