Visual Basic (2008 Express) | ||
Standard Functions
VB has many of these. A simple example is Len - the function that calculates the number of characters in a string. The code here assigns the number of characters in a string called Surname to an integer variable called Count.
|
||
Dim
Surname As String Dim Count As Integer Surname = "Johnson"Count = Len(Surname)
|
This code would assign the value 7 to the variable Count. | |
Sub-routines
To define a subroutine in VB, a programmer needs to give it a name. Here is an example of a subroutine named InitialiseTextBox that initialises some of the properties of a TextBox...
|
||
Private
Sub
InitialiseTextBox(ByVal
MyTextBox As
TextBox)
MyTextBox.Width = 50
|
If you want to use this subroutine on other forms, replace the word Private by the word Public. | |
The programme would need to tell the subroutine which
TextBox is to be initialised. This is done through the parameter
MyTextBox (you can name it whatever you
like!).
The next code uses this subroutine to initialise a TextBox called txtCount and outputs the number of letters in the string Surname. |
||
Dim
Surname As String Dim Count As Integer Surname = "Johnson"Count = Len(Surname) InitialiseTextBox(txtCount) txtCount.Text = Count
|
||
|
The output is displayed in the TextBox. | |
Functions
A Function returns an answer - the type of the answer has to be declared in the function heading... Here is an example of a function called Lettern that calculates how many times the letter n occurs in a string.
|
||
Private
Function
Lettern(ByVal
MySurname As String)
As Integer
Dim Count As
Integer Dim i As Integer 'Initialise count to zero If Mid$(MySurname, i, 1) = "n" Then Count = Count + 1 End If Next 'Assign value to the function
|
Note that the value of the
function must always be assigned to it.
A parameter called MySurname is used to pass the identifier of the string to the function. |
|
To use this function to output the answer into our
Textbox...
|
||
Dim
Surname As String Dim Count As Integer Surname = "Johnson"Count = Len(Surname) InitialiseTextBox(txtCount) 'This next instruction calls the function
|
||
Modules | ||
Useful subroutines and functions should be placed in a Module.
This module can then be used in other programs.
Subroutines and functions placed in the Module and declared Public, can be used on any form in the current project. To create a Module in VB, right-click on the name of the Project and Add...Module
|
||
|
The module will appear in the Solution Explorer.
This module is saved as a separate file and can be imported into other programming projects. |
|
Back |