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.
Nesting Levels
Control structures in Visual Basic can be nested to as many levels as you want. It is common practice to make nested structures more readable by indenting the body of each one. The integrated development environment (IDE) editor automatically does this.
In the following example, the procedure sumRows 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
In the preceding example, the first Next statement closes the inner For loop and the last Next statement 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.
No comments:
Post a Comment