This browser is no longer supported.
Upgrade to Microsoft Edge to take advantage of the latest features, security updates, and technical support.
- 13 contributors
Declares the name of a module and introduces the definition of the variables, properties, events, and procedures that the module comprises.
attributelist Optional. See Attribute List .
accessmodifier Optional. Can be one of the following:
See Access levels in Visual Basic .
name Required. Name of this module. See Declared Element Names .
statements Optional. Statements which define the variables, properties, events, procedures, and nested types of this module.
End Module Terminates the Module definition.
A Module statement defines a reference type available throughout its namespace. A module (sometimes called a standard module ) is similar to a class but with some important distinctions. Every module has exactly one instance and does not need to be created or assigned to a variable. Modules do not support inheritance or implement interfaces. Notice that a module is not a type in the sense that a class or structure is — you cannot declare a programming element to have the data type of a module.
You can use Module only at namespace level. This means the declaration context for a module must be a source file or namespace, and cannot be a class, structure, module, interface, procedure, or block. You cannot nest a module within another module, or within any type. For more information, see Declaration Contexts and Default Access Levels .
A module has the same lifetime as your program. Because its members are all Shared , they also have lifetimes equal to that of the program.
Modules default to Friend access. You can adjust their access levels with the access modifiers. For more information, see Access levels in Visual Basic .
All members of a module are implicitly Shared .
Classes and Modules
These elements have many similarities, but there are some important differences as well.
Terminology. Previous versions of Visual Basic recognize two types of modules: class modules (.cls files) and standard modules (.bas files). The current version calls these classes and modules , respectively.
Shared Members. You can control whether a member of a class is a shared or instance member.
Object Orientation. Classes are object-oriented, but modules are not. So only classes can be instantiated as objects. For more information, see Objects and Classes .
Modifiers. All module members are implicitly Shared . You cannot use the Shared keyword when declaring a member, and you cannot alter the shared status of any member.
Inheritance. A module cannot inherit from any type other than Object , from which all modules inherit. In particular, one module cannot inherit from another.
You cannot use the Inherits Statement in a module definition, even to specify Object .
Default Property. You cannot define any default properties in a module. For more information, see Default .
Access Level. Within a module, you can declare each member with its own access level. Module members default to Public access, except variables and constants, which default to Private access. When a module has more restricted access than one of its members, the specified module access level takes precedence.
Scope. A module is in scope throughout its namespace.
The scope of every module member is the entire module. Notice that all members undergo type promotion , which causes their scope to be promoted to the namespace containing the module. For more information, see Type Promotion .
Qualification. You can have multiple modules in a project, and you can declare members with the same name in two or more modules. However, you must qualify any reference to such a member with the appropriate module name if the reference is from outside that module. For more information, see References to Declared Elements .
- Class Statement
- Namespace Statement
- Structure Statement
- Interface Statement
- Property Statement
- Type Promotion
The .NET documentation is open source. Provide feedback here.
Submit and view feedback for
Visual Basic Modules and Procedures
A key part of developing applications using Visual Basic is ensuring that the code is carefully structured. This involves segmenting the code into projects , modules and procedures so that it is easy to understand and maintain.
A complete Visual Basic application is typically contained in a single project . Within a project , code is placed in separate code files called modules , and within each module , the Visual Basic code is further separated into self contained and re-usable procedures .
The topic of projects was covered in Creating a New Visual Basic Project . In this chapter we will look in detail at Visual Basic modules and procedures.
Visual Basic Code Modules
Visual Basic application source code is structured into module files with a .vb suffix. By default, Visual Studio creates a separate module file for each form in an application containing the code to construct the form. For example, the code to create a form called Form1 will be placed in a module file named Form1.Designer.vb . Similarly, any code that has been defined by the developer to handle events from controls in the form will be placed by Visual Studio into a module file called Form1.vb .
When writing additional Visual Basic for an application, the code should ideally be logically grouped to together with other source code in a module file. When we say logically grouped we mean that the code should be grouped with other code of a similar nature. For example, code to work with files might be placed in a module called FileIO.vb, while mathematical procedures might all reside in a file named Math.vb. The idea is to ensure Visual Basic code is placed in a file where it makes sense for it to be located. This will differ between applications, but it is worth investing the time to ensure code is well structured as doing so makes subsequent maintenance of the code by you or other developers much easier.
We mentioned previously that Visual Studio places the code to construct each form in separate module files. We now need to learn how to create a new module in a project to contain our own Visual Basic code. Begin by creating a new Windows Application project in Visual Studio called vbModules . Add two TextBox controls (named value1TextBox and value2TextBox) and a button (labeled Calculate) to the Form so that appears as follows:
Once the new project has been opened and the first form is visible, select Add Module... from the Project menu. The Add Item window will appear with the Module item pre-selected:
Name the new module Math.vb and click the Add button. The new module will be added to the project and a new tab labeled Math.vb for accessing the module code appears in the design area:
Now that we have added a new module to our project the next step is to add Visual Basic code to that module. Before we can do that, however, we need to learn about Visual Basic procedures .
Visual Basic Code Procedures
Visual Basic procedures provide a way to break up code into logical and re-usable sections that can be called from other sections of Visual Basic code. For example, you might have a section of Visual Basic code that calculates the interest due on a loan. It is also possible that you need to perform this calculation from a number of different places in your application code. Rather than duplicating the code to perform this task at each code location where it is needed, it is more efficient to place the calculation code in a procedure, and then call that procedure each time it is needed.
Visual Basic provides two types of procedures:
- functions - Functions are procedures which perform a task and return a value when completed.
- subroutines - Subroutines are procedures which perform a task but return no value when completed.
It is especially useful to be able to return values from functions . For example, the function may need to return the result of the task it performed (perhaps the result of a calculation). A function might also return a True or False value to indicate when the task was performed successfully. The Visual Basic code which called the function then acts based on the returned value.
In the case of both subroutines and functions , values (known as parameters ) may optionally be passed into the procedure.
Defining Visual Basic Subroutines
Subroutines are declared inside Visual Basic Modules. Our newly created module in Visual Studio contains the following:
We are now going to add a subroutine called DisplayResult to this module. The syntax for a Visual Basic subroutine is as follows:
scope Sub subroutineName(parameters) End Sub
The scope value is either Private or Public depending on whether the Subroutine is to be accessible from Visual Basic code outside of the current module. Sub is the Visual Basic keyword which indicates this is a Subroutine rather than a Function. subroutineName is the name of the Subroutine and is used when this specific procedure is to be called. The parameters value allows the parameters accepted by this Subroutine to be declared (see below).
The Public keyword indicates the scope . This defines whether this subroutine is accessible from Visual Basic code residing in other modules. Setting the scope to Private would make the Subroutine inaccessible to Visual Basic code outside the current module.
The Sub keyword indicates that this is a Subroutine (as opposed to a Function) and as such, does not return a value on completion. Finally, the name of the Subroutine is provided. The parentheses are used to hold any parameters which may be passed through to the Subroutine when it is called. The End Sub code marks the end of the Subroutine. The Visual Basic code that constitutes the Subroutine is placed after the Subroutine declaration and the End Sub .
We can write code in the Subroutine to display a message window as follows:
Next, the Click event procedure of the button in our form needs to call the DisplayResult() Subroutine. Double click on the button in the form to display the event procedure code and add the call to DisplayResult() as follows:
Once the above change has been made, press F5 to build and run the application. When the application is running, pressing the button should cause a message window to appear displaying the text "Test Message".
Passing Parameters to Functions and Subroutines
Parameters may be passed to both Functions and Subroutines in Visual Basic. Parameters may be passed by value or by reference . When a parameter is passed by value, the Function or Subroutine receives a copy of the data. As such, changes to the data do not affect the original object or variable. When parameters are passed by reference, however, the Function or Subroutine receives a pointer to the original variable or object. As such, any changes made in the Subroutine are made directly to the original variable or object. Parameters that are passed by value must be prefixed with the keyword ByValue in the Function or Subroutine declaration. Parameters passed by reference , however, are prefixed by the ByRef keyword. If no keyword is specified, ByVal is is assumed.
The parameter must also be named in the Subroutine or Function declaration together with the variable or object type. For example, to adapt the DisplayResult() Subroutine to accept an Integer parameter called result by value, and display the result in the message window:
Alternatively, to pass the parameter by reference:
Just for the sake of completeness, change the Button control event procedure to pass through a string (note that we will change this later to pass the result of the actual calculation):
Press F5 to build and run the application. The message window should now display 'Result is 10'.
Defining Visual Basic Functions
Visual Basic Functions differ from Subroutines in that they return a value. The syntax for declaring a Function is as follows:
scope Function functionName(parameters) As datatype
The scope value is either Private or Public depending on whether the Function is to be accessible from Visual Basic code outside of the current module. Function is the Visual Basic keyword that indicates that this is a Function rather than a Subroutine. functionName is the name of the function. parameters allows the parameters accepted by this Function to be defined. Finally, datatype defines the type of value returned by the Function.
With this syntax in mind we can create a Function for our application that will accept the values from our two text fields as parameters, perform the calculation and return the result as an Integer:
In the above Function, we accept two strings (value1 and value2) and declare an Integer variable called result to hold the result of the calculation. We then divide value1 by value2 and multiply the result by 100 to get value1 as a percentage of value2. The result is assigned to the result variable and then returned to the code which called the function.
The final step, is to modify our Button control Click event procedure to call the PercentageOf() function, passing through the Text properties of our two TextBox controls. The result returned by this function is then passed to the DisplayResult() Subroutine where it is displayed in a message window:
After making the above change, press F5 to build and run the application. Enter 10 into the left hand TextBox control, 100 into the right hand TextBox control and press the Calculate button. The MessageBox will appear declaring that the result is 10.
- View source
- View history
- iOS / iPhone / iPad
- VMware Server
- Xen Virtualization
- Windows Server 2008
- Red Hat Linux
- Linux eBooks
- Ubuntu Linux
- Fedora Linux
- Fedora Desktop
- OpenSUSE Desktop
- Visual Basic
- Ad Blocking Survival
- Web Development
- eBook Store
- This page was last modified on 27 October 2016, at 20:13.
- Copyright 2023 Payload Media, Inc. / Neil Smyth. All Rights Reserved.
- About Techotopia
- Mobile view
- API & MACROS
- PDM PROFESSIONAL (EPDM) API
- DOCUMENT MANAGER API
- EDRAWINGS API
- VISUAL BASIC
Modules in Visual Basic
Modules are containers to define custom functions, procedures or variables to group code in Visual Basic.
Module containing an entry point subroutine (main) is an entry module. It is always at least one module defined in the Visual Basic macro.
In order to add new module it is required to RMB (right mouse button click) the Modules folder and select Inset->Module command
Module must have an unique name which can be defined by the developer.
Functions defined in module are public. Members (variables) declared with Dim keyword are only visible within this module scope and not visible for another modules, while members declared with Public keyword are visible for this and other modules. Refer Variables Scope article for more information.
Module members are available in IntelliSense after typing the name of the module followed by . symbol.
- PyQt5 ebook
- Tkinter ebook
- SQLite Python
- wxPython ebook
- Windows API ebook
- Java Swing ebook
- Java games ebook
- MySQL Java ebook
Organizing code in Visual Basic
last modified January 10, 2023
In this part of the Visual Basic tutorial we show how to organize code. We cover modules, procedures and namespaces, and the scope.
Visual Basic statements are organized into blocks, modules, classes and namespaces. This helps to make the code more maintainable and robust. Correct code organization prevents from making errors in the code.
The basic building blocks of a Visual Basic program are:
- Procedures and functions
An assembly is a DLL or exe file. An assembly is a compiled code library for use in deployment, versioning and security. A namespace is an abstract container providing context for the items. A module is a reference type available throughout its namespace. Classes are basic building blocks of an OOP program. A procedure is a unit of a program that is created to do a specific task. A block is the lowest level organisation of Visual Basic statements provided by some keywords like If or While . A statement is an atom in a Visual Basic program, a smallest unit of code.
Closely related to this topic is the scope and duration of a variable. A scope is the visibility of the declared variable.
A lifetime of a variable is a period of time during which a variable holds a value. Local variables exists as long as the procedure is executing. After that, they are not available anymore. However, if we declare a variable to be Static, the variable continues to exist after the procedure terminates. Module, Shared and instance variables exist for the lifetime of the application.
The basic example
First, we cover some basics.
In this example, we have a Module called Example . Inside the example, we have a Main subroutine. The statement that prints some message to the console is placed within the Main procedure. Event the most simple Visual Basic programs must be properly organized.
The exact example, now without the module. We can put the code inside a class too. The Main procedure must be declared Shared , because the class is not instantiated. The compiler calls the Main method without creating an instance of the class. That is why it must be declared Shared . Java and C# work the same.
Namespaces are used to organize code at the highest logical level. They classify and present programming elements that are exposed to other programs and applications. Within a namespace, we can declare another namespace, a class, an interface, a structure, an enumeration, or a delegate.
In the following code, we have two files that share the same namespace.
We have a ZetCode namespace. In the namespace, we have a module Example1 .
We declare a namespace called ZetCode .
In the module, we declare and initialise a x variable.
We have an Init method, in which we work with the x variable.
In the second file, we work with the Init method from the previous file.
We work in the same namespace.
We call the Init procedure and work with the x variable. Both the procedure and the x variable are defined in a different file and different module. But they are defined in the same namespace, so we can use them.
The following code example has two distinct namespaces. We use the Imports keyword to import elements from a different namespace.
We have a skeleton of a Math class in a MyMath namespace. In the Basic class, we define a PI constant and a GetPi method.
In this file, we use the elements from the MyMath namespace.
We import the elements from the MyMath namespace into our namespace.
Now we can use those elements. In our case the PI variable and the GetPi method.
Note that we do not need the Imports keyword. In the example, it is commented out. We can use elements from other namespaces by using fully qualified names of the elements.
A module is used to organize code and wrap up variables, properties, events, and procedures of similar use. Unlike a class, a module is not a type. A module can be created in a namespace or in a file. A module cannot be created inside another module, class, structure, interface or block. All members in a module are implicitly Shared. Modules have a Friend access. This means that a module is accessible everywhere in an assembly.
We have three modules defined. The first two modules have variables and procedures. These will be used in the third module.
We can use access specifiers inside modules too. This way we can control the accessibility of the elements in the modules.
We print the x and y variables. They are Public and are accessible from a different module. We may use the module name to fully specify the variable name.
A scope is a visibility of a variable. A variable with a module scope is available within the module, where it was declared.
We have x variable inside the module. The variable is available in all three procedures.
This is a variable with a module scope. It is declared outside any procedure.
Inside the proc2 procedure, we increase the x variable and print its contents to the console. We refer to the x variable defined in the module.
Procedures provide modularity to the code project. They should do only a specific task.
In the preceding code example, we have three procedures beside the main procedure. The three procedures create a local x variable and print it to the terminal. The main procedure refers to the module x variable.
The proc1 procedure creates a local x variable. This variable shadows the one, declared at a module scope.
The main procedure prints 0. The other procedures print 100 to the terminal. They create their local x variables, initiate them to 0, increase by 100.
It is important to understand that variables declared within a block of code like If / End If or While / End While have a limited block scope and lifetime. The next example illustrates this.
We have an x variable declared Inside the If / End If block.
The variable is not available outside the block. If we uncomment the second line, the example will not compile.
This part of the Visual Basic tutorial was dedicated to organizing code.
Visual Basic Modules and Procedures
All executable statements in Visual Basic must belong to a procedure . A procedure is a block of code enclosed between a Sub . . . or Function . . . statement and a matching End Sub or End Function statement. Once you have written a procedure, it can be called by a program statement (sometimes referred to as the calling code ) somewhere else in your program. This is known as making a procedure call . When the procedure has finished executing, it will (usually) return control to the procedure that called it (the calling procedure ).
A procedure contains all of the code necessary to carry out a particular task. Once we have created the procedure, we can call it every time we need to carry out that task. Procedures thus reduce the total amount of code we need to write in order to implement a program. Procedures also allow us to construct our program from a number of discrete building blocks, each of which contains only the code it needs to achieve its allotted task and communicate with other parts of the program. Furthermore, because a procedure has such a specific role, it is easy to determine whether the procedure's code is working as intended. Procedures thus facilitate the testing and debugging of programs.
The applications we have created so far have all had a single form, and all of the code for the application has been contained within the form's class definition. For relatively small-scale applications like the ones featured in these pages, that's perfectly acceptable. For larger applications, which may require thousands or even tens of thousands of lines of code in order to implement a program, the task of updating and maintaining the program code can rapidly become unmanageable unless we can impose some kind of structure on it - which is where modules come in.
A module is a file that contains a number of related procedures. Just as a procedure groups together the program instructions required to carry out a particular task, a module groups together procedures that carry out closely related tasks. For example, we could group together procedures that carry out file-handling tasks in one module, and procedures dedicated to manipulating graphic images in various ways in another module.
It is often the case that procedures written for one application can be used in another application with little or no modification. If these procedures are placed in a separate module, they can easily be imported into any project that needs them. The ability to reuse code in this way represents the potential to significantly reduce the amount of time and resources required to complete a project. In this page we will be taking a somewhat closer look at procedures. Before we do that, let's create a Visual Basic module.
- Create a new project called "Modules"
- Change the Text property of the main form to "Geometry"
- Change the name of the form to "frmGeometry"
- Set the application's Startup Object property to Modules.frmGeometry .
- Add controls to the form as shown below (we have used a form size of 300 x 240)
Your form should look like this screenshot
- Change the names of the controls as specified in the table below
The form's code module is created when the form is created, and is where the form's code will usually be found. On this occasion, however, we are going to create a separate code module to hold re-usable procedures. To create a module:
- Click on Project ► Add Module . . . . You will see the following dialogue box:
The Add New Item ► Modules dialogue box
- Change the default filename to " modGeometry.vb ", and click Add . The code editor window will open and display the new module's code window. Any code you create here will be available to other parts of your project, and the module itself will appear in the Solution Explorer window.
The procedures we use fall into two general categories: those that are provided by the Visual Basic programming language, and those we create ourselves. Beyond this distinction, however, there are two quite different kinds of Visual Basic procedure - subroutines and functions . So far, we have not really discussed the differences between these different kinds of procedure in any detail.
We'll talk about subroutines first, because nearly all of the procedures we have created in our example programs up to now have been subroutines. A subroutine is created by typing the Sub keyword, followed by a procedure name (which should be chosen to reflect the purpose of the subroutine), followed by parentheses. To end the subroutine, we type the keywords End Sub . The general syntax of a subroutine declaration is shown below, and should be familiar to you.
Sub ProcedureName () . . . End Sub
A widely used convention for naming subroutines (and procedures in general) is to start the name of the subroutine with a capital letter. If a combination of words is used, each new word should begin with a capital letter, e.g. CalculatePrice , or PrintRecord . The code that is placed between the Sub and End Sub statements is called the body of the subroutine, and defines what the subroutine actually does. The variables required by a subroutine - there can be any number of these - can be declared within the body of the subroutine as follows:
Sub ProcedureName() Dim strFirstName As String strFirstName = "Fred" End Sub
The actions performed by the subroutine will depend on the program statements that make up the body of the subroutine. The above procedure simply declares a string variable called strFirstName , and assigns it the value "Fred". Let's create a couple of subroutines for our Geometry application. We'll place these subroutines in our newly created modGeometry module.
- In the module's code editor window (between Module modGeometry and End Module ), enter the following code:
Sub SquarePerimeter() Dim dblSide As Double Dim dblPerimeter As Double dblSide = frmGeometry.txtSide.Text dblPerimeter = dblSide * 4 frmGeometry.txtPerimeter.Text = dblPerimeter End Sub Sub SquareArea() Dim dblSide As Double Dim dblArea As Double dblSide = frmGeometry.txtSide.Text dblArea = dblSide * dblSide frmGeometry.txtArea.Text = dblArea End Sub
When we use a procedure, we are said to be calling the procedure. To call a subroutine, we type its name in the section of code where it is to be used. We are now going to call the subroutines defined in the modGeometry module from the application's form:
- Open the form designer window and double-click the Calculate Perimeter button. The code editor window for the form will open and you will see that the following code has been created:
Private Sub cmdPerimeter_Click(sender As Object, e As EventArgs) _ Handles cmdPerimeter.Click End Sub
- In the body of the subroutine, type " SquarePerimeter() "
- Now go back to the form designer window and double-click the Calculate Area button. Within the body of its subroutine, type " SquareArea() ".
- Go back to the form designer window once more and double-click the Exit button. Within the body of its subroutine type " End ".
The code in your code editor window should now look like this:
Your form's code should look like this
- Run and test the application to check that it works (you will need to type a value into the box labelled "Side" before clicking on the Calculate Perimeter or Calculate Area buttons). You should see something like the following:
Output from the Geometry program
Functions are procedures, just like subroutines. Unlike a subroutine, however, a function sends a value back to the routine that calls it (it is said to return a value). When creating a function, a slightly different syntax is used, as we shall see. To illustrate the use of functions, we need to modify our form somewhat, as follows (note that we have changed the size of the form to 180 × 340 pixels):
The amended frmGeometry form
- Name the form controls as follows (some controls stay as they were):
We create a function by typing the Function keyword, followed by a procedure name (which should be chosen to reflect the purpose of the function), followed by parentheses. Because the function (unlike a subroutine) returns a value, you should specify the data type of the value the function will return by typing the As keyword to the right of the closing parenthesis, followed by the datatype of the value to be returned. To end the function, type the keywords End Function . The general syntax of a function declaration is shown below.
Function ProcedureName() As DataType . . . End Function
The naming conventions used for fuctions are the same as those used for subroutines. As with subroutines, the code that is placed between the Function and End Function statements is called the body of the function, and defines what the function actually does. The variables required by the function - again, there can be any number of these - can be declared within the body of the function as follows:
Function GreetAlien() As String Dim strGreeting As String strGreeting = "Hello and welcome to Earth!" GreetAlien = strGreeting End Function
The actions performed by the procedure will depend on the program statements that make up the body of the function. The above function simply declares a string variable called strGreeting and assigns it the value "Hello and welcome to Earth!". The function returns a value with the datatype String . The value actually returned by a function is determined by typing the name of the function, followed by an equals sign ( = ), followed by the name of the variable that holds the value to be returned. In the above example, the function returns the string value "Hello and welcome to Earth!".
Let's add some functions to our modGeometry module.
- Open the module's code editor window, delete the existing subroutines, and enter the following code:
Function RectPerimeter() As Double Dim dblLength As Double Dim dblHeight As Double dblLength = CDbl(frmGeometry.txtLength.Text) dblHeight = CDbl(frmGeometry.txtHeight.Text) RectPerimeter = (dblLength + dblHeight) * 2 End Function Function RectArea() As Double Dim dblLength As Double Dim dblHeight As Double dblLength = CDbl(frmGeometry.txtLength.Text) dblHeight = CDbl(frmGeometry.txtHeight.Text) RectArea = dblLength * dblHeight End Function
A function is called in much the same way as a subroutine, by typing its name in the section of code where it is to be used. The main difference is that the value returned by the function is assigned to a variable. In the following example, the function GreetAlien() is called when the form loads:
Private Sub Form_Load() Dim strCaption As String strCaption = GreetAlien() End Sub
The primary purpose of a function is to return a value. In the above example, the return value of the GreetAlien() function is assigned to the variable strCaption when the form loads.
Let's call the functions we have added to the modGeometry module:
- In the frmGeometry class definition, delete the click event handlers for the cmdPerimeter button and the cmdArea button.
- Open the form designer window and double-click the Calculate button. The code editor window for the form will open and you will see that the following code has been created:
Private Sub cmdCalculate_Click(sender As Object, e As EventArgs) _ Handles cmdCalculate.Click End Sub
- In the body of this procedure, enter the code shown below:
txtPerimeter.Text = RectPerimeter() txtArea.Text = RectArea()
- Run and test the application to check that it works (you will need to type values into the Length and Height boxes before clicking on the Calculate button). You should see something like the following:
Output from the new version of the Geometry program
Arguments and parameters
In the subroutines and functions examined above, calculations are made using the values entered into various text boxes on our form by the user. Although these procedures work perfectly well, they are explicitly coded to work with the values of these particular external variables, and therefore cannot be used in any other context. In order to make the procedures more generic - and thus reusable - we need to rewrite them to accept values from different sources. External values can be passed in to a procedure for processing, rather than being hard-wired into the procedure itself. The external values accepted by a procedure for processing are called arguments .
In Visual Basic, a list of the arguments that will be accepted by a procedure will appear within parentheses following the procedure name in a Sub . . . or Function . . . statement. The general syntax used for a subroutine that takes one or more arguments is as follows:
Sub ProcedureName(Argument[,Argument . . .]) . . . End Sub
And here is the construction used for a function:
Function ProcedureName(Argument[,Argument . . .]) As DataType . . . End Function
When we write a procedure that can accept arguments, we need to tell the procedure how many arguments it will receive and specify the datatype for each argument. We also need to name each argument so that the code within our procedure can differentiate between the arguments passed to the procedure. We achieve this by declaring the name and datatype of each argument within the parentheses that follow the Sub ProcedureName or Function ProcedureName statement as a comma-separated list.
It is worth pausing here to clarify what we mean by the terms "argument" and "parameter" - since both terms are used in the heading for this section, and so far we have not mentioned parameters at all! Although the two terms are often used interchangeably, they do in fact have subtly different meanings.
The term argument refers to the actual value passed to a procedure. The term parameter (or formal parameter ) refers to the declaration of the argument's name and datatype within parentheses in the Sub . . . or Function . . . statement that begins the procedure declaration. The list of arguments within parentheses is called a formal parameter list .
A procedure can accept any number of arguments, and each argument can be of a different type. The example below declares a subroutine called CalculatePrice that takes a double-precision floating point variable called dblItemPrice and an integer variable called intQty as its arguments.
Sub CalculatePrice(dblItemPrice As Double, intQty as Integer) Double dblPrice = intQty * dblItemPrice . . . End Sub
We could also write a function that takes the same arguments as the subroutine, but assigns the result of the calculation to its return value (a double-precision floating point value):
Function CalculatePrice(dblItemPrice As Double, intQty as Integer) As Double Double dblPrice = intQty * dblItemPrice CalculatePrice = dblPrice End Function
Procedures can use the arguments passed to them in exactly the same way they use locally declared variables. To demonstrate the use of arguments in procedures, modify the RectPerimeter() and RectArea() functions in your code module as follows:
Function RectPerimeter(dblLength As Double, dblHeight As Double) RectPerimeter = (dblLength + dblHeight) * 2 End Function Function RectArea(dblLength As Double, dblHeight As Double) RectArea = dblLength * dblHeight End Function
To call a procedure that takes one or more arguments, we type its name, followed by comma separated list of arguments within parentheses. The number of arguments should match the number of parameters specified in the procedure's formal parameter list. The arguments must be provided in the same order in which they appear in formal parameter list, and have the specified datatype.
In order for our application to work, we need to revise the code for the Calculate button as follows:
Private Sub cmdCalculate_Click(sender As Object, e As EventArgs) _ Handles cmdCalculate.Click Dim dblInputLength, dblInputHeight As Double dblInputLength = CDbl(txtLength.Text) dblInputHeight = CDbl(txtHeight.Text) txtPerimeter.Text = RectPerimeter(dblInputLength, dblInputHeight) txtArea.Text = RectArea(dblInputLength, dblInputHeight) End Sub
Once you have made the necessary changes, run the program again to test it.
Passing by reference
Each argument passed to a procedure usually consists of the current value of some variable. We call this passing by value , and it effectively makes a copy of the variable available to the procedure - the value of the original variable is not changed by anything the procedure does. Sometimes, however, we actually want a procedure to change the value of a variable. We can achieve this through a technique called passing by reference .
When we pass by reference, the argument passed to a procedure is the address in memory of a variable rather than its value. Any change the procedure makes to the value of the argument is applied to the original variable , not a copy. In order to pass a variable to a procedure by reference , we use the ByRef keyword before the name of the argument within the parentheses of the function declaration. To demonstrate this technique, make the following changes to the RectArea() function:
Public Function RectArea _ (dblLength As Double, dblHeight As Double, ByRef dblArea As Double) RectArea = dblLength * dblHeight dblArea = RectArea End Function
Now make the following changes to the code for the Calculate button:
Private Sub cmdCalculate_Click(sender As Object, e As EventArgs) _ Handles cmdCalculate.Click Dim dblInputLength, dblInputHeight, dblArea As Double dblArea = 0 dblInputLength = CDbl(txtLength.Text) dblInputHeight = CDbl(txtHeight.Text) txtPerimeter.Text = RectPerimeter(dblInputLength, dblInputHeight) RectArea(dblInputLength, dblInputHeight, dblArea) txtArea.Text = dblArea End Sub
Note that the changes we have made mean that the value of dblArea is passed to the RectArea() function by reference , which means that the value of dblArea will be changed by this function call. Note also that by default , even though we do not use the ByVal keyword in front of the formal parameters dblLength As Double and dblHeight As Double for the RectArea() function, these variables will be passed to the function by value . Variables are only passed to a function by reference if the ByRef keyword is used.