Share via


Visual Basic Concepts

Function Procedures

Visual Basic includes built-in, or intrinsic functions, like Sqr, Cos or Chr. In addition, you can use the Function statement to write your own Function procedures.

The syntax for a Function procedure is:

[Private|Public][Static]Functionprocedurename (arguments) [Astype]statements

End Function

Like a Sub procedure, a Function procedure is a separate procedure that can take arguments, perform a series of statements, and change the value of its arguments. Unlike a Sub procedure, a Function procedure can return a value to the calling procedure. There are three differences between Sub and Function procedures:

  • Generally, you call a function by including the function procedure name and arguments on the right side of a larger statement or expression (returnvalue = function()).

  • Function procedures have data types, just as variables do. This determines the type of the return value. (In the absence of an As clause, the type is the default Variant type.)

  • You return a value by assigning it to the procedurename itself. When the Function procedure returns a value, this value can then become part of a larger expression.

For example, you could write a function that calculates the third side, or hypotenuse, of a right triangle, given the values for the other two sides:

Function Hypotenuse (A As Integer, B As Integer) _
As String
   Hypotenuse = Sqr(A ^ 2 + B ^ 2)
End Function

You call a Function procedure the same way you call any of the built-in functions in Visual Basic:

Label1.Caption = Hypotenuse(CInt(Text1.Text), _
CInt(Text2.Text))
strX = Hypotenuse(Width, Height)

For More Information   For additional details about the Function procedure, see "Function Statement" in the Language Reference. The techniques for calling all types of procedures are discussed in the section, "Calling Procedures," later in this chapter.