Loops
For Next
Code Syntax
Examples
Basic Use
Sub AddNumbers()
Dim Total As Integer
Dim Count As Integer
Total = 0
For Count = 1 To 10
Total = Total + Count
Next Count
MsgBox Total
End Sub
Sub AddEvenNumbers()
Dim Total As Integer
Dim Count As Integer
Total = 0
For Count = 2 To 10 Step 2
Total = Total + Count
Next Count
MsgBox Total
End Sub
Sub HghlightNegative()
Dim Rng As range
Set Rng = range("A1", range("A1").End(xlDown))
Counter = Rng.Count
For i = 1 To Counter
If WorksheetFunction.Min(Rng) >= 0 Then
Exit For
End If
If Rng(i).Value < 0 Then
Rng(i).Font.Color = vbRed
End If
Next i
End Sub
Do While
Code Syntax
Examples
General Use
Sub AddFirst10PositiveIntegers()
Dim i As Integer
i = 1
Do While i <= 10
Result = Result + i
i = i + 1
Loop
MsgBox Result
End Sub
Sub EnterCurrentMonthDates()
Dim CMDate As Date
Dim i As Integer
i = 0
CMDate = DateSerial(Year(Date), Month(Date), 1)
Do While Month(CMDate) = Month(Date)
range("A1").Offset(i, 0) = CMDate
i = i + 1
If i >= 10 Then
Exit Do
End If
CMDate = CMDate + 1
Loop
End Sub
Do Until
Code Syntax
Behave Same us Do whileFor Each
Basic Syntax
Examples
Basic Usage
- Use the ‘Exit For’ statement in the For Each-Next loop to come out of the loop.