Do While/Until Loop

c. Do While Loop
   In this case you need to give condition.
   While your given condition is still true/false , it will execute the code.

For example


Type the code above in your vba editor
Run the code.

Output should be like this.

Explanation:
While the value of that range is 1, it will input "The value is one" in the second column.
Once the next cell is no longer 1, it will end the code.

Why do I need to declare the value of x as 1?
Of course, your program doesn't know which row you want to start.

So, your first row is cells (1,1) or A1.

Then, it will check the condition if true or false.

If its true, it will execute the code.

Then, to increase the row number you need to add the value of x in order to loop continuously.

In the second loop, value of x is 2 (1+1). Need to increment the value of x.
In this case, value of x is incremented by 1.

d. Do Until Loop
  Similar to Do While Loop except for a condition that the code will be executed until the 
   Code will stop until the condition is true.

  We will use the example from Do While Loop
   

Type the code above in your vba editor
Run the code.

Output should be like this

Explanation:
String "The cell has value" will be inputted to column be while the cell in column A is not empty.
When the code encounter the empty cell, it will stop.

FYI, I just seldom used this Do While/Until Loop.


Our next lesson is If Then Statement.




No comments:

Post a Comment