70 likes | 247 Views
Function Procedures. Function Procedures. Visual Basic includes built-in functions, like Sqr, Cos or Len, Left, Mid, Right. In addition, you can use the Function statement to write your own Function procedures. The syntax for a Function procedure is:.
E N D
Function Procedures • Visual Basic includes built-in functions, like Sqr, Cos or Len, Left, Mid, Right. • In addition, you can use the Function statement to write your own Function procedures. • The syntax for a Function procedure is: [Private|Public] Functionprocedurename (arguments) [Astype]statements End Function
Function Procedures • 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 (other than through it’s arguments) to the calling procedure.
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 function name.
The function in this example calculates the third side, or hypotenuse, of a right triangle, given the values for the other two sides: Function Hypotenuse (A As Single, B As Single) As Single 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: Width = Val(Text1.Text) Height = Val(Text2.Text) Label1.Caption = Hypotenuse(Width, Height)
Private Sub cmdConvert_Click() picTempC.Cls picTempC.Print FtoC(Val(txtTempF.Text)) End Sub Private Function FtoC(t As Single) As Single 'Convert Fahrenheit temperature to Celsius FtoC = (5 / 9) * (t - 32) End Function
Private Sub cmdCompute_Click() Dim radius As Single, height As Single picOutput.Cls Call InputDims(radius, height) Call ShowAmount(radius, height) End Sub Private Function CanArea(radius As Single, height As Single) As Single 'Calculate surface area of a cylindrical can CanArea = 6.28 * (radius * radius + radius * height) End Function Private Sub InputDims(radius As Single, height As Single) radius = Val(InputBox("Enter radius of can:")) height = Val(InputBox("Enter height of can:")) End Sub Private Sub ShowAmount(radius As Single, height As Single) picOutput.Print "A can of radius"; radius; "and height"; height picOutput.Print "requires"; CanArea(radius, height); "square units to make." End Sub