In previous Article, we had seen about For Next Loop. In this article we are going to see about While and Do While Loop.
Example: Let’s take the same example what we discussed in previous Article with For..Next Loop.. Calculate the Sum of all Numbers from 1 to 10 Natural Numbers.
iCount=1 sum = 0 While iCount
You can see that in While Loop, unlike For loop, we need to increment the Counter variable value by your own. In for loop, you can see, that we need not to mention iCount= iCount + 1 to increment the value of i by 1 in every iterations.
There are two ways of using DO...While Loop. 1. You can put the Condition before getting in to the Loop. 2. You can check the condition at the end of the loop. It means, in this case Loop will be executed once even if the Condition is failing at the first time itself.
Syntax: Type 1
Do While [condition]
Syntax: Type 2
Loop While [condition]
Example: Let's take the same example what we discussed above. Calculate the Sum of all Numbers from 1 to 10 Natural Numbers. We will put the example using While condition at the starting and at the end of the loop.
1. Condition in the starting of the loop
iCount=1 sum = 0 Do While iCount
1. Condition in the starting of the loopiCount = 1 sum = 0 Do sum = sum + iCount iCount = iCount + 1 Loop While iCount
Note:For putting your condition you can use "Until" keyword instead of While See the below Example:iCount = 1 Sum = 0 Do Sum = Sum + iCount iCount = iCount + 1 Loop Until iCount > 10
But you can see that when you are using the keyword until then you need to change the Condition. For both While or until you can not use the same condition. Because "Until" is like reverse of "While".
To Check out more Excel Macro Tutorials, visit Excel Macro Tutorial