• Hi All

    Please note that at the Chandoo.org Forums there is Zero Tolerance to Spam

    Post Spam and you Will Be Deleted as a User

    Hui...

  • When starting a new post, to receive a quicker and more targeted answer, Please include a sample file in the initial post.

IF condition (Loops)

nawin83

New Member
Hi All,


I am new to this blog and found that its very useful to learn the excel and VBA.


I just started learning VBA on my own recently, but i am facing problem in writing IF condition (Loops) in my code. I tried many times to understand the code using Google, but still not able to write it on my own.


So, kindly some one explain me how to use below Loops with simple techinque.


Loop Structure

*For…Next

*For…Each…Next

*Do…While

*Do…Until

*Do…Loop…While

*Do…Loop…Until

*While…Wend


Thanks,

Nawin
 
Welcome to the forums!


First, I'd recommend reading this thread:

http://chandoo.org/forums/topic/do-loop-with-cells

or this post by Chandoo:

http://chandoo.org/wp/2011/08/30/variables-conditions-loops-in-vba/


Finally, here's a short macro containing all examples:

[pre]
Code:
Sub Example()
'For...next
'Often used when you have a defined number of things you want to do
For i = 1 To 10
Cells(i, "A").Value = i
Next

'For...each...next
'Used when I want to do something to each "thing" within a group
For Each ws In ThisWorkbook.Worksheets
'Unhide all the worksheets in this workbook
ws.Visible = True
Next

'Do while
'Perform an action while a condition is met
Range("A2") = 1
Do While Range("A2") < 10
Range("A2") = Range("A2").Value + 1

Loop

'Do Loop While
'Similar to above, slightly different wording
Range("A2") = 1
Do
Range("A2") = Range("A2").Value + 1
Loop While Range("A2") < 10

'Do Until
'Perform some action UNTIL something is met
Range("A1") = 1
Do Until Range("A1") = 10
Range("A1") = Range("A1") + 1

Loop

'do loop until
'Again, similar to above, just different wording
Range("A1") = 1
Do
Range("A1") = Range("A1") + 1
Loop Until Range("A1") = 10

'While...Wend
'Do some action as long as something else is true
Range("B1") = 1
While Range("B1").Value < 10
Range("B1") = Range("B1") + 1

Wend

End Sub
[/pre]
More examples:

http://www.ozgrid.com/VBA/loops.htm

http://vbatutor.blogspot.com/2009/02/excel-vba-macro-tutorial-looping.html
 
Thanks Luke for your response on my query.


I will go through the above coding and will also refer the links and get back to you, if still need any clarification.


Regards,

Nawin:)
 
Back
Top