Chapter 17. Subroutines and Functions

Subroutines and functions enable you to break an otherwise unwieldy chunk of code into manageable pieces. They allow you to extract code that you may need to use under more than one circumstance and place it in one location where you can call it as needed. This not only reduces repetition within your code; it also enables you to maintain and update the code in a single location.

A subroutine performs a task for the code that invokes it. A function performs a task and then returns some value. The value may be the result of a calculation, or a status code indicating whether the function succeeded or failed.

Together, subroutines and functions are sometimes called routines or procedures. They are also sometimes called methods, particularly when they are subroutines or functions belonging to a class. Subroutines are also occasionally called sub procedures or less formally subs.

This chapter describes subroutines and functions. It explains the syntax for declaring and using each in a Visual Basic application. It also provides some tips for making routines more maintainable.

SUBROUTINES

A Sub statement defines the subroutine's name. It declares the parameters that the subroutine takes as arguments and defines the parameters' data types. Code between the Sub statement and an End Sub statement determines what the subroutine does when it runs.

The syntax for defining a subroutine is as follows:

[attribute_list] [inheritance_mode] [accessibility] _
Sub subroutine_name([parameters] ...

Get Visual Basic® 2010 Programmer's Reference now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.