gabriel-t
10/13/2017 - 4:54 PM

5. Programming Loops

Sub DoUntilExample()
    Dim counter As Integer
    counter = 1
    Do Until counter > 5
      counter = counter + 1
      MsgBox counter
    Loop
End Sub

'Similar to Do While. Below is an example if you need to bail out early from any loop

Sub DoUntilExample()
    Dim counter As Integer
    counter = 1
    Do Until counter > 5
        If counter = 0 Then
            Exit Do
        Else
            counter = counter + 1
            MsgBox counter
        End If
    Loop
End Sub
    
Sub DoWhileExample()
    Dim counter As Integer
    counter = 1
    Do While counter < 5
        Cells(counter, "D").Value = counter
        counter = counter + 1
    Loop
End Sub

'Do While [CONDITION]
  '[SOMETHING]
'Loop
Cells.item(1,1)
Cells.item(1,"A")
Cells(1,1)
Cells(1,"A")
'Use to reference the cells on your spreadsheet. The above all select the same cell. See below how it can be useful..

Sub TimesTable()
    Dim StartNumber As Integer
    Dim EndNumber As Integer
    Dim answers As Integer
    Dim TimesTable As Integer
    
    EndNumber = 10
    TimesTable = 10
    
    For StartNumber = 1 To EndNumber
    
        answer = StartNumber * TimesTable
        Cells(StartNumber, 1).Value = StartNumber & " times " & TimesTable & " = "
        Cells(StartNumber, 1).Offset(, 1).Value = answer
    Next StartNumber
  
End Sub
    
Sub ForEachLoop()
    For Each mycell In Range("A2:A6")
        mycell.Value = Replace(mycell, "-", "")
    Next mycell
End Sub

'For Each variable_name In collection_name
'Next variable_name
Sub LoopExample()
    Dim StartNumber As Integer
    Dim EndNumber As Integer
    EndNumber = 5
    For StartNumber = 1 To EndNumber
        answer = answer + StartNumber
    Next StartNumber
    MsgBox answer
    'MsgBox shows 15 (= 1+2+3+4+5)
End Sub

'For StartNumber = 1 To EndNumber Step 2
  'StartNumber: Starting point for the loop is 1. You have to assign a value.
  'Step: Optional. Default to go from start number to the end number in steps of 1 each time round the loop. It goes in steps of 2 in this case.
'Next: Followed by the variable name you typed after the word For on line 5.