Home -> Programming -> Subroutines -> Functions

Functions

Using Functions

Visual Basic contains a plethora of predefined functions which exist for our convenience. By using them we avoid having to write the code ourselves to accomplish the task at hand. It is a good rule of thumb not to do something yourself which is already done for you - less work after all. There are several different categories of functions. Lets first look at the data conversion functions. These convert data from one data type to another. A variable or literal is passed to the function in place of the 'arg' shown in the list. In all the following examples aVar must be appropriately declared!

Conversion Functions

Data Type Checking Function

An example of using one of these is:

    aVar = CInt(3.14159265)
    The number passed has decimals but they are ignored because we are doing an integer conversion. The value stored is 3.

or

    aVar = CSng(5)
    This puts the value 5.0 into aVar.

Of course it doesn't make much sense to convert a value into its own data type. What is the point?

You can also do some of these conversions by appending the function call to the end of an variable.

An example of using one of these is:

    aVar = (3.14159).ToString
    This converts the value 3.14159 to a string of ASCII digits and stores it in aVar. It looks the same but it is not a number and therefore can no longer be manipulated using math operations..

There is another aspect to the .ToString conversion. This function can also be used to format numbers in various ways. For example to show a number as dollars we would code as follows:

    aVar = (56.283).ToString("c")
    This would output the number as a string with the format $56.28. It adds a dollar symbol to the left and truncates the digits to two.

or to control floating point numbers:

    aVar = (56.283).ToString("f")
    This would output the number as a string with the format 56.283.

or to format as dollars and cents the hard way:

    aVar = (56.283).ToString("$ #,###.##")
    This creates the same output as the currency formatting above: $56.28. The key to using the symbols is as follows:

Symbols for Custom Formatting

String Functions

There are also a whole set of string functions. These help you manipulate strings to create whatever your desired output might be. There are several more special string functions than are listed here!

An example of this would be:

    aVar = "Now is the time".ToUpper
    The contents of aVar would then be: "NOW IS THE TIME"

There are literally dozens more functions. Here are some of the more common ones. If you need something different consult VB's help system for a comprehensive list.

    aVar = Len("Hello World")
    The contents of aVar would then be the length of the string in characters, in this example: 11.

    aVar = Microsoft.VisualBasic.Left("Hello World", 5)
    The contents of aVar would then be the first five characters from the string, in this example: "Hello".

    aVar = Microsoft.VisualBasic.Right("Hello World", 5)
    The contents of aVar would then be the last five characters from the string, in this example: "World".

    aVar = Mid("Mount Royal College", 1, 5)
    The contents of aVar would then be the first word of the string, in this example: "Mount".

    aVar = Mid("Mount Royal College", 13, 7)
    The contents of aVar would then be the last word of the string, in this example: "College".

    aVar = Mid("Mount Royal College", 7)
    The contents of aVar would then be the rest of the string of the string starting at character 7, in this example: "Royal College".

There are dozens more functions. Here are some of the more common ones. If you need something different consult VB's help system for a comprehensive list.

Math Functions

    aVar = Math.Sqrt(16)
    The contents of aVar would be: the square root of 16 which is 4.

    aVar = Math.Round(8.6)
    The contents of aVar would then be: 9.

    aVar = Math.PI
    The contents of aVar would be: the value of PI.

Character Functions

    aVar = Chr(65)
    The numeric argument is the ASCII code value for the ASCII character. In the example shown the value would be "A".

    aVar = Asc("A")
    The argument is a character and the value returned will be the ASCII value of it. In the example shown the value would be 65. This is the opposite function to Chr()

    aVar = ChrW(CharCode)
    This function is for Unicode characters. CharCode must be a number between -32,768 to 65,535.

    aVar = AscW(Character)
    The argument is a character and the value returned will be the Unicode value of it. This is the opposite function to ChrW()

Special Note

Every time we use a function, we call it and assign it into a variable. If we do not assign it into a variable, then the result from calling the function will be lost. The only time we don't need to assign a function to a variable is if we are using the return result of the function to immediately perform a comparison.

Creating a Function

A function is a code segment similar to a procedure but slightly different. Whereas a procedure may only perform an action and usually does, a function may perform an action and usually does, not but it always returns a result. Since it returns a result, it cannot stand alone. This is why the Special Note appears above. When you call or use the function the result must either be used on the spot or stored in another variable. Here is an example similar to the one shown in the procedure section. This is how it could be created as a function. The declaration is similar to a procedure with three differences. These are highlighted in the code below.

Private Function Circumference(ByVal radius as Single) as Single
    'Calculate the radius of a circle given the value of its radius
    Return 2 * 3.14159 * radius
End Sub

The first difference is the use of the keyword Function rather than Sub. This is how VB differentiates procedures and functions. The second difference is the inclusion of a type statement on the end of the declaration. This is necessary because a function must return a value, so the type of the value to be returned must be declared at the end of the function declaration. The third difference is that we have to write code the so that the value is returned. This is normally done by using the keyword Return and then following it with the value to be returned, or a calculation which will produce the value to be returned. So much for declaring and writing the code for a function, but how do we use it.

Assuming we have a button named btnCalculate and assuming we double-click it to produce an event-procedure, we could include the following code to calculate and display the circumference in an appropriate label. The function call is emphasized.

Private Sub btnCalculate_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnCalculate.Click
    'Calculate the circumference and display it
    theRadius = CSng(txtRadius.Text)
    lblCircumference.Text = Circumference(theRadius)
End Sub

We call the function by typing its name and including any needed parameters. (The editor will prompt you to supply any declared parameters, even those you write yourself.) Notice that we have used an assignment statement to assign the return value of the function into the property lblCircumference.Text which will cause the result of the calculation to be displayed on the form.

Note! We do not write a function to put the result of the circumference calculation into a textbox because we would have to know the name of the textbox ahead of time. This would limit the usefulness of such a function. So we create functions to do calculations (e.g. circumference) and leave the assignment of the result of such calculations to the programmer, to be done in the main form's procedures. This way such calculations can be programmed once only but called as many times as we need to use them.