Nested Control Structures (Visual Basic)
Nested Control Structures (Visual Basic)
For the latest documentation on Visual Studio 2017 RC, see Visual Studio 2017 RC Documentation.
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.
PublicSubsumRows(ByVala(,)AsDouble,ByRefr()AsDouble)
Dimi,jAsInteger
Fori=0ToUBound(a,1)
r(i)=0
Forj=0ToUBound(a,2)
Ifa(i,j)>0Then
r(i)=r(i)+a(i,j)
EndIf
Nextj
Nexti
EndSub
In the preceding example, the first Next statement closes the inner For loop and the last Next statement closes the outer For loop.
https://msdn.microsoft.com/enus/library/8y82wx12.aspx 1/3
1/25/2017 NestedControlStructures(VisualBasic)
Likewise, in nested If statements, the EndIf 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.
Note
For many control structures, when you click a keyword, all of the keywords in the structure are highlighted. For instance, when you click If in an If...Then...Else
construction, all instances of If, Then, ElseIf, Else, and EndIf in the construction are highlighted. To move to the next or previous highlighted keyword, press
CTRL+SHIFT+DOWN ARROW or CTRL+SHIFT+UP ARROW.
ForEachctlAsSystem.Windows.Forms.ControlInMe.Controls
Withctl
.BackColor=System.Drawing.Color.Yellow
.ForeColor=System.Drawing.Color.Black
If.CanFocusThen
.Text="Colorschanged"
IfNot.Focus()Then
'Insertcodetoprocessfailedfocus.
EndIf
EndIf
EndWith
Nextctl
The Visual Basic compiler detects such overlapping control structures and signals a compiletime error.
See Also
Control Flow
Decision Structures
Loop Structures
Other Control Structures
2017 Microsoft
https://msdn.microsoft.com/enus/library/8y82wx12.aspx 3/3