A procedure is a block of Visual Basic statements enclosed by a declaration statement and an End statement. All Visual Basic code is written within procedures.
A procedure is invoked from some other place in the code. When it is finished executing, it returns control to the code that invoked it; this code is known as the calling code. The calling code is a statement, or an expression within a statement, that specifies the procedure by name and transfers control to it.
Types of Procedures
Visual Basic uses several types of procedures:
- Sub procedures perform actions but do not return a value to the calling code.
- Event-handling procedures are Sub procedures that execute in response to an event triggered by user action or by an occurrence in a program.
- Function procedures return a value to the calling code.
- Property procedures return and assign values of properties on objects or modules.
Procedures and Structured Code
Every line of code in your application must be inside some procedure, such as
Button1_Click. If you subdivide large procedures into smaller ones, your application is more readable.
Procedures are useful for performing repeated or shared tasks, such as frequently used calculations, text and control manipulation, and database operations. You can call a procedure from many different places in your code, so you can use procedures as building blocks for your application.
Structuring your code with procedures gives you the following benefits:
- Procedures allow you to break your programs into discrete logical units. You can debug separate units more easily than you can an entire program without procedures.
- You can use procedures developed for one program in other programs, often with little or no modification.