Tuesday, July 26, 2011

Looping in VBA

See the Same Result with Different Type of Loops


 Sub FLoop()
 Dim i As Integer
  Range("A1").Value = "Example By For Loop"
  Range("A2").Select
 
    For i = 1 To 20
                ActiveCell.Value = "i am In For Loop " & i & " time and My value is " & i
                ActiveCell.Offset(1, 0).Select
    Next
 End Sub


 Sub DoLoop()
 Dim i As Integer
  Range("A1").Value = "Example By Do Loop"
  Range("A2").Select
  i = 0
                Do
                i = i + 1
                ActiveCell.Value = "i am In Do Loop " & i & " time and My value is " & i
                ActiveCell.Offset(1, 0).Select
                Loop Until i = 20
   
 End Sub


Sub WhileLoop()
 Dim i As Integer
  Range("A1").Value = "Example By While Loop"
  Range("A2").Select
  i = 0
                While i <> 20
                i = i + 1
                ActiveCell.Value = "i am In While Loop " & i & " time and My value is " & i
                ActiveCell.Offset(1, 0).Select
                Wend
   
 End Sub


Sub LableLoop()
 Dim i As Integer
  Range("A1").Value = "Example By lable and Goto"
  Range("A2").Select
  i = 0
CC:
   
              i = i + 1
                ActiveCell.Value = "i am In Goto Loop " & i & " time and My value is " & i
                ActiveCell.Offset(1, 0).Select
     If i <> 20 Then
     GoTo CC:
     Else
     Exit Sub
     End If
 End Sub



No comments: