Nested Control Statements
You can place control statements inside other control statements, for example an If...Then...Else block within a For...Next loop. A control statement placed inside another control statement is said to be nested.
Control statements in Visual Basic can be nested to as many levels as you want. It is common practice to make nested decision structures and loops more readable by indenting the body of each one.
In the following example, the procedure adds together the positive elements of each row of the matrix:
Public Sub SumRows(ByVal A(,) As Double, ByRef R() As Double) Dim I, J As Integer For I = 0 To UBound(A, 1) R(I) = 0 For J = 0 To UBound(A, 2) If A(I, J) > 0 Then R(I) = R(I) + A(I, J) End If Next J Next I End Sub
Notice that the first Next closes the inner For loop and the last Next closes the outer For loop. Likewise, in nested If statements, the End If statements automatically apply to the nearest prior If statement. Nested Do loops work in a similar fashion, with the innermost Loop statement matching the innermost Do statement.