VB6 Tutorial 58: Function Procedures

By | 2018-05-31

A function procedure in Visual Basic 6 has a scope, a unique name, parameter list and return value. You can pass any datatype to a procedure e.g Integer, Boolean, Long, Byte, Single, Double, Currency, Date, String and Variant.

Object data types and arrays are also supported. This is same for the return type values.

Difference between argument and parameter

The value you’re passing, while calling the function, is called argument and the variable, in the function definition, that will receive the value is called parameter. Both the terms are used for the same value.

Example

In this example, 32 and 54 are passed to the function ‘sum’ from Form_Load procedure.

'Function Definition 
Private Function sum(n1 As Integer, n2 As Integer) 'n1, n2 are 'parameters
    Text1.Text = n1 + n2
End Function
Private Sub Form_Load()
    Text1.Text = ""
   'Function callgin
    Call sum(32, 54)   '32 and 54 are arguments   
End Sub

Function procedure that returns value

Example

'Function Definition 
Private Function sum(n1 As Integer, n2 As Integer) As Integer
    'Returns a value
    sum = n1 + n2    
End Function
Private Sub Form_Load()
    Text1.Text = "" 
    'Function calling and assigning the returned value 
    Text1.Text = sum(60, 40)   
End Sub

Passing arguments: By Value or By Reference

You can pass an argument either by value or by reference. Arguments are passed by value using the ByVal keyword and by reference using the ByRef keyword or by omitting any specifier.

While passing the arguments by reference, references of the variables are passed. So if the argument is passed by reference, it can be modified by the called procedure and the original value of the argument in the calling procedure will be changed. But the argument value will be unchanged if you call the procedure using constants or expressions as parameters.

Example

'Calling procedure
Private Sub Command1_Click()
    Dim a As Integer     'The value of a is 0 after declaration
    Call num(a)
    Print a   'Value of a is 1, modified
End Sub
'Called procedure
Public Function num(ByRef x As Integer) 'You may omit ByRef
    x = x + 1
End Function

On the other hand, when the arguments are passed by value, the actual values are passed. So the called procedure cannot change their original values in any way.

Example

'Calling procedure
Private Sub Command1_Click()
    Dim a As Integer    'The value of a is 0 after declaration
    Call num(a)
    Print a  'The value of a is 0, its unchanged
End Sub
'Called procedure
Public Function num(ByVal x As Integer)
    x = x + 1
End Function

Note: Both Sub and Function procedures can accept parameters.

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.