Function Procedure & Return by Value in Visual Basic 2010

Function Procedure & Return by Value in Visual Basic 2010

Functions:

A function(s) is a group of statements in Visual Basic which is used to do a task. It is very similar to Subs which we studied in the last tutorial. The main difference between subs and functions is that a sub doesn’t return a value to its calling piece of code while a functions does return a value to its calling piece of code.

A function is always enclosed by Function and End Function statements.

Functions can be of 2 major types.

  1. Built-in Functions: They are functions which are already defined in Visual Basic. Such as MsgBox () function and InputBox () function. We have briefly discussed about these 2 in the previous articles.
  2. User-defined Functions: They are defined by the user themselves. Follow this article to know more about them.

Functions Declaration:

The syntax for declaring a functions procedure is as follows:

Functions Example:

  1. Create a button on your form and modify its properties as you want. (we named the button in our form as “Function”)
  2. Double click on the button and it will lead you to the code window.
  3. Create a user defined functions below the Private Sub – End Sub. You can also go on with the code we have typed.

Output:

Function Output 1

Important: The return type of the functions can be of various other data types.

  Sub Procedures & Input Boxes in Visual Basic 2010

Passing Values to the Functions (ByVal)

Visual Basic supports passing an argument to a functions procedure either By Value or By Reference. This passing mechanism determines whether the procedure can modify the element or not. Both the passing mechanisms are carried out by the keywords ByVal and ByRef. You can choose the ByVal when you do not want the procedure to change the value of the variable.

ByVal Example:

  1. Drag and drop 2 text boxes and a button on your form.
  2. Modify their properties as you want.
  3. Follow the syntax below and modify your code.

Output:

Function Output 2

Calculator: (with basic operations)

Code:

Output:

Addition:

Addition

Subtraction:

Subtraction

Multiplication:

Multiplication

Division:

Function Division

Feel free to post your comments, send us your tutorials and ask for tutorials @ www.codejow.com

Previous Sub Procedures and Input Boxes in Visual Basic 2010
Next Design a Basic Calculator with Basic math operators in Visual Basic 2010

About author

Bahonar Javid
Bahonar Javid 43 posts

<p>* Computer Application Student<br /> * Co-Founder of www.codejow.com<br /> * Love to code and Learn new languages<br /> * Enjoy playing football</p>

View all posts by this author →

You might also like