|Important||This document may not represent best practices for current development, links to downloads and other resources may no longer be valid. Current recommended version can be found here.|
How to: Break Large Pieces of Code into Smaller Pieces
All executable statements in Visual Basic must be inside some procedure, such as Main, Form1_Load, or calculateTotal. It is possible to write your entire application as a single large procedure, but if you divide it into smaller ones, your code is more readable.
Structured programming is an approach that emphasizes program modularity and a hierarchical structure within an application. In Visual Basic, the most straightforward way to achieve structured programming is through judicious use of procedures to break your application into discrete logical units. You can debug each individual unit more easily than the entire program. You can also use a procedure developed for one program in other programs, often with little or no modification.
To break a large procedure into self-contained pieces
Identify one or more self-contained sections of your code.
For each self-contained section, move the source code outside the large procedure and surround it with the Sub and End Sub statements.
At the place in your large procedure from which you removed the code section, add a statement that calls the Sub procedure.
If it is useful for the new procedure to return a value to the large procedure, you can define a Function procedure.
To break out a section that returns a value
Surround the removed source code with Function and End Function statements instead of Sub and End Sub.
At the place where the Function procedure has the value ready to return to the calling code, add a Return statement.
At the place in your large procedure from which you removed the code section, make sure the calling statement does something with the returned value. You can store it in a variable or use it in an expression.